ASP.NET MVC 4 and MVCContrib Grid: Render Checkbox for each TR and Post values in complex type

瘦欲@ 提交于 2019-12-04 22:17:24

I would recommend you to use a real view model that will reflect the requirements of your view (displaying a grid containing for each row a checkbox, and displaying the id and name of the item and retrieving those values in a list in your postback action):

public class CheckBoxViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool CheckBox { get; set; }
}

public class ViewModel
{
    public IPagination<CheckBoxViewModel> List { get; set; }
}

and then have your view strongly typed to this view model:

@model ViewModel

@using (Html.BeginForm("SendData", "Home", FormMethod.Post))
{
    @Html.Grid(Model.List).Columns(c =>
    {
        c.For(x => x.Id);
        c.For(x => x.Name);
        c.For(x => Html.Partial("Partial/CheckBoxTemplate", x)).Named("Options");
    })

    <button type="submit">OK</button>
}

finally your partial could look like this:

@model CheckBoxViewModel

@{
    var index = Guid.NewGuid().ToString();
}

@Html.Hidden("list.Index", index)
@Html.Hidden("list[" + index + "].Id", Model.Id)
@Html.Hidden("list[" + index + "].Name", Model.Name)
@Html.CheckBox("list[" + index + "].CheckBox", Model.CheckBox)

Now when the SendData action is invoked it will be passed the list of your view model.

Alternatively you could use the Html.BeginCollectionItem helper presented in the following article which would allow you to use the strongly typed versions of the helpers:

@model CheckBoxViewModel
@using(Html.BeginCollectionItem("list")) 
{
    @Html.HiddenFor(x => x.Id)
    @Html.HiddenFor(x => x.Name)
    @Html.CheckBoxFor(x => x.CheckBox)
}

Recommended further reading: Model Binding To A List.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!