Nathan McKaskle Nathan McKaskle - 3 months ago 7
C# Question

Display Annotation Not Working In Create View

For some reason it works in the index view for table headers but not for the create view.

Here's the relevant part of my model in the controller:

[Required(ErrorMessage = "Status is required.")]
[Display(Name = "Status")]
public int StatusId { get; set; }


I also have lazy loading:

public virtual Status status { get; set; }


I even added it to the Status model:

[Required(ErrorMessage = "Status is required.")]
[MaxLength(50)]
[Display(Name = "Status")]
public string StatusName { get; set; }


Here it is in the view:

<div class="form-group">
@Html.LabelFor(model => model.StatusId, "StatusId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("StatusId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.StatusId, "", new { @class = "text-danger" })
</div>


Yet it doesn't show up in the actual create page as "Status":

enter image description here

Same thing happens with another one in the same model. What's the deal?

Answer

Because you are using the below overload where you are explicitly providing the text to be displayed.

public static MvcHtmlString LabelFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    string labelText,
    IDictionary<string, object> htmlAttributes
)

The second parameter in the overload you are using is the labelText which will be displayed in the label.

Use this overload

public static MvcHtmlString LabelFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    object htmlAttributes
)

So your code will be

@Html.LabelFor(model => model.StatusId, new { @class = "control-label col-md-2" })
Comments