ASP.NET MVC多个复选框 [英] ASP.NET MVC Multiple Checkboxes

查看:187
本文介绍了ASP.NET MVC多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约20项的列表我要显示给用户与每个人旁边的复选框(A 可用属性)。

I have a List of about 20 items I want to display to the user with a checkbox beside each one (a Available property on my ViewModel).

当表单提交,我希望能够通过一个通过我的视图模型的选择属性检查回到我的控制器方法每个复选框的值。

When the form is submitted, I want to be able to pass the value of each checkbox that is checked back to my controller method via the Selections property on my ViewModel.

我会如何去这样做使用MVC表单辅助类?这甚至可能?

How would I go about doing this using the Form Helper class in MVC? Is this even possible?

PS:我不希望一个列表框,用户可以只突出多个项目。

PS: I don't want a listbox where the user can just highlight multiple items.

推荐答案

模型:

public class MyViewModel
{
    public int Id { get; set; }
    public bool Available { get; set; }
}

控制器:

public class HomeController: Controller
{

    public ActionResult Index()
    {
        var model = Enumerable.Range(1, 20).Select(x => new MyViewModel
        {
            Id = x
        });
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<MyViewModel> model)
    {
        ...
    }
}

查看〜/查看/主页/ Index.cshtml

@model IEnumerable<AppName.Models.MyViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

编辑模板〜/查看/主页/ EditorTemplates / MyViewModel.cshtml

@model AppName.Models.MyViewModel
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.Available)

这篇关于ASP.NET MVC多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆