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.