user3857185
user3857185

Reputation:

Asp.NET: Get all of the values from the list of object in a model when submitting a form

I have a model that contains a list where I loop some properties inside a form. When I clicked the save button to save the list, the list inside the model is null.

So how will I get the list with values? I want to get all of the selected bar and process it in saving which bar were added to the Foo.

Here are my sample codes.

ViewModel:

public class FooViewModel
{
   public FooViewModel()
   {
      BarList = new List<BarViewModel>();
   }

   public List<BarViewModel> BarList { get; set; }
}

public class BarViewModel
{
   public string BarId { get; set; }
   public bool IsSelected { get; set; }
}

Controller:

public ActionResult AddBar(int id, string otherId)
{
   //omitted the codes
}

[HttpPost]
public ActionResult AddBar(int id, string otherId, FooViewModel model)
{
   //omitted the codes
}

View:

@model FooViewModel

@using (Html.BeginForm("AddBar", "Foo", FormMethod.Post, new { role = "form", autocomplete = "off", enctype = "multipart/form-data" }))
{
    @foreach (var bar in Model.BarList)
    {
        @Html.HiddenFor(bar => bar.Id)
        @Html.CheckBoxFor(bar => bar.IsSelected)   
    }
}

Upvotes: 0

Views: 590

Answers (1)

Red
Red

Reputation: 2776

You should change your cycle over BarList to use for loop instead of foreach.

@for (var i = 0; i < Model.BarList.Length; i++ )
{
    @Html.HiddenFor(mdl => mdl.BarList[i].Id)
    @Html.CheckBoxFor(mdl => mdl.BarList[i].IsSelected)   
}

This way, correct ids and names will be added to <hidden> and <input> tags, so that MVC will be able to do correct model binding over it.

You can read a bit more about model binding and collections in the Internet, like here for instance: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Upvotes: 2

Related Questions