jeudi 24 septembre 2015

ASP.NET MVC cannot POST view model with binding to checkbox

I have a top level view model MyListViewModel that has some properties (Id and Name) and then a list of another type that I will use for checkbox (I've called it MySingleViewModel).

public class MySingleViewModel
{
    public MyObjectType MyObject { get; set; }
    public bool Selected { get; set; }
}

public class MyListViewModel
{
    public Guid Id { get; set; }
    public String Name { get; set; }
    public IList<MySingleViewModel> MyObjects { get; set;}
}

My view:

@using (Html.BeginForm("AddObject", "MyController", FormMethod.Post))
{
    for (var i = 0; i < Model.MyObjects.Count(); i++)
    {
        <div class="form-group">
            @Html.DisplayFor(model => model.MyObjects[i].MyObject.Name)
            @Html.CheckBoxFor(model => model.MyObject[i].Selected)

            @Html.HiddenFor(model => model.Id)
            @Html.HiddenFor(model => model.Name)
        </div>        
    }

    <input type="submit" class="btn btn-success" value="Save"/>
}

My controller:

[HttpPost]
public void AddObject(MyListViewModel model)
{
    //do things    
}

I had an inspection of the POST data and it is:

MyObjects[0].Checked=true
MyObjects[0].Checked=false
MyObjects[1].Checked=false
MyObjects[2].Checked=false
MyObjects[3].Checked=true
MyObjects[3].Checked=false

For the boxes I've ticked there are 2 entries, one true and one false. Is this normal?

Also in the controller, what I get back is:

model.Id = {00000000-0000-0000-0000-000000000000}
model.Name = null
model.MyObjects = null

Obviously since the form isn't actually posting the view model I want back to the controller, this happens. Is there any way to pass the required view model back to the controller since I need the Id and Name?




Aucun commentaire:

Enregistrer un commentaire