MVC Html Helper: modelmetadata from string expression
I am trying to build an html helper that would have access to modelmetadata. I need both versions of helper to work: from string expression and from lambda expression: Example:
public static MvcHtmlString MyLabel(this HtmlHelper html, string htmlFieldName)
{
return LabelHelper(html, htmlFieldName);
}
public static MvcHtmlString MyLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
return LabelHelper(html, ExpressionHelper.GetExpressionText(expression));
}
private MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName)
{
ModelMetadata m = ModelMetadata.FromStringExpression(htmlFieldName);
// the rest of the code...
}
The problem with the code above is that it will not work for complex types. For example, if my Model looked like this:
public class MyViewModel
{
public int Id { get; set; }
public Company Company { get; set; }
}
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
My html helper will fail to read metadata for the following:
@Html.MyLabel("Company.Name")
I could make it work for the helper that takes an expression because ModelMetadata.FromLambdaExpression(...)
actually works fine with complex objects, but that is not enough for me.
Any suggestions are appreciated.
In a word, it will not be possible to use only the FromStrinExpression(...) method. Internally the ModelMetadata.FromStringExpression(...) will try to get the ViewDataInfo for the nested property - "Name" in your case. If the View is a stongly-typed, but the Model is null then the
ViewData.GetViewDataInfo will return null. In this case it will loop only the ModelMetadata.Properties and will not be able to find the nested property. If the Model is not null, then the method will return the correct ModelMetadata, because of the correct ViewDataInfo. The ModelMetadata.FromLamdaExpression(...) on the other has enough information about the container and the type of the property and that is why it works with complex objects.
I have one brave suggestion :). You have the string expression and the Html.ViewData. You can loop the Html.ViewData.ModelMetadata.Properties recursively and try to get the ModelMetadata for the nested property.
链接地址: http://www.djcxy.com/p/19084.html