For this view model:
public class ParentViewModel
{
public object ChildViewModel { get; set; }
}
If I use Html.LabelForas follows:
@Html.LabelFor(model => model.ChildViewModel)
I would get this conclusion:
<label for="Model_ChildViewModel">ChildViewModel</label>
What I really want, but for the generated label, use the attribute DisplayNameapplied to the EG object
[DisplayName("My Custom Label")]
public class ChildViewModel
{
}
with output:
<label for="Model_ChildViewModel">My Custom Label</label>
I understand that a method Html.LabelForaccepts an expression that expects a property, and it will look for an attribute DisplayNamefor that property, not the object itself.
I created an Html helper method to achieve what I want it to look like this:
public static IHtmlString CreateLabel<TModel>(this HtmlHelper html, Func<TModel, object> func)
where TModel : class
{
TagBuilder tb = new TagBuilder("label");
var model = html.ViewData.Model as TModel;
if (model != null)
{
object obj = func(model);
if (obj != null)
{
var attribute = obj.GetType().GetCustomAttributes(
typeof(DisplayNameAttribute), true)
.FirstOrDefault() as DisplayNameAttribute;
if (attribute != null)
{
tb.InnerHtml = attribute.DisplayName;
return MvcHtmlString.Create(tb.ToString());
}
else
{
tb.InnerHtml = obj.ToString();
return MvcHtmlString.Create(tb.ToString());
}
}
}
tb.InnerHtml = html.ViewData.Model.ToString();
return MvcHtmlString.Create(tb.ToString());
}
Instead of accepting the expression, my helper accepts Func<TModel, object>which returns the object that I want to check for the attribute DisplayName.
, , , :
@Html.CreateLabel(model => model.ChildObject)
:
The type arguments for method 'CreateLabel<TModel>(this HtmlHelper,
Func<TModel, object>) cannot be inferred from usage. Try specifying
the arguments explicitly.'
:
@{ Html.CreateLabel<ChildViewModel>(model => model.ChildObject); }
. , , .
, :
, , . , MVC . TagBuilder, , <legend></legend>. . .
public static IHtmlString LegendTextFor<TModel, TObject>(this HtmlHelper<TModel> html, Expression<Func<TModel, TObject>> expression)
{
return LegendTextHelper(html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
expression.Compile().Invoke(html.ViewData.Model));
}
private static IHtmlString LegendTextHelper<TModel, TObject>(this HtmlHelper<TModel> html, ModelMetadata metadata, string htmlFieldName, TObject value)
{
string resolvedLabelText = metadata.DisplayName ?? value.GetDisplayName() ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText))
return MvcHtmlString.Empty;
return MvcHtmlString.Create(resolvedLabelText);
}
private static string GetDisplayName<T>(this T obj)
{
if (obj != null)
{
var attribute = obj.GetType()
.GetCustomAttributes(typeof(DisplayNameAttribute), false)
.Cast<DisplayNameAttribute>()
.FirstOrDefault();
return attribute != null ? attribute.DisplayName : null;
}
else
{
return null;
}
}