Razor: If model is List<> then @Html.LabelFor creates empty “for” field

前端 未结 2 1323
Happy的楠姐
Happy的楠姐 2021-01-20 09:03

If the model is a list of objects then @Html.LabelFor model => model[i].member) creates an empty for attribute. The DisplayName works properly,

2条回答
  •  深忆病人
    2021-01-20 09:49

    The @model declaration assigns the model object to the Model variable (note the captial 'M'). But then you are reading from model, which hasn't been assigned.

    Try this:

      @model List
      // form code removed for brevity
            @for (var i = 0; i < Model.Count; i++) {
                
    @Html.LabelFor(model => Model[i].ClickMe)
    @Html.EditorFor(model => Model[i].ClickMe, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => Model[i].ClickMe, "", new { @class = "text-danger" })
    }

    That doesn't explain why your second example works at all, but hey, give this a try.

提交回复
热议问题