Return List from view to controller in MVC 3

前端 未结 3 567
梦毁少年i
梦毁少年i 2020-12-11 08:54

I currently have an object Tag defined as follows:

public class Tag
{
    public string Name { get; set; }
}

Now, this is a co

3条回答
  •  时光说笑
    2020-12-11 09:04

    If you can add a bool IsChecked property to your Tag model then you can just use EditorFor (or CheckBoxFor) in a loop. The trick is to use a for loop with indexer (not foreach) such that you access the property via the views main model. Then the modelbinder will do the rest for you so your POST action will receive MyModel with its Tags IsChecked properties set to the correct states.

    Models:

    public class Tag
    {
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }
    
    public class MyModel
    {
        public string Name { get; set; }
        public List Tags { get; set; }
    }
    

    The View:

    @model MyMvcApplication.Models.MyModel
    @using (Html.BeginForm())
    {
        
    @Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name)
    @for (int i = 0; i < Model.Tags.Count; i++) { @Html.DisplayFor(x => Model.Tags[i].Name) @Html.EditorFor(x => Model.Tags[i].IsChecked) }
    }

提交回复
热议问题