开发者

MVC3 editor template for IEnumerable doesn't generate 'for' attribute in @Html.LabelFor

I have custom EditorTemplate for my ViewModel class (it generates a checkbox list).

In view my model is IEnumerable<ViewModel>, but when I call @Html.EditorForModel() in generated HTML for attribute of label tag is empty.

Everything works fine when I want to render only one checkbox.

public class StateViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

EditorTemplate:

@model Mcs.Sibs.UI.Web.Models.StateViewModel

@Html.HiddenFor(x => x.Id)
<div>
    @Html.CheckBoxFor(x => x.Checked)
    @Html.LabelFor(x => x.Checked, Model.Name)
</div>

My View:

@model IEnumerable<Mcs.Sibs.UI.Web.Models.StateViewModel>
@using (Html.BeginForm()
{    
    @Html.EditorForModel()
}

Generated HTML looks like this (for one checkbox):

<input type="hidden" value="1" name="[0].Id" data-val-required="The Id field is    required." data-val-number="The field Id must be a number." data-val="true">
<div>
<input type="checkbox" value="true" name="[0].Checked" data-val-required="The Checked   field is required." data-val="true">
<input type="hidden" value="false" name="[0].Checked">
<label for="">Checkbox label</label>

You ca开发者_如何学运维n see that 'for' attribute is empty. Am I doing something wrong or this is some kind of bug in MVC3 default EditorTemplate for IEnumerable<T>?


Try this:

@Html.EditorFor(model => model)


I had this problem too and after about an hour of non-working solutions I solved using an additional ViewModel to wrap the IEnumerable collection.

Please try the following code:

public class MyViewModel
{
    public List<StateViewModel> StateViewModels { get; set; }
}

Then, in your view:

@model IEnumerable<Mcs.Sibs.UI.Web.Models.MyViewModel>
@using (Html.BeginForm()
{    
    @Html.EditorFor(m => m.StateViewModels)
}

The id and for attributes will be correctly generated.
Of course you can adapt the names of the models to your naming conventions :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜