在的CheckBoxList MVC3查看并得到检查项目传递给控制器 [英] CheckboxList in MVC3 View and get the checked items passed to the controller

查看:112
本文介绍了在的CheckBoxList MVC3查看并得到检查项目传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类MoreInfo:

I have a class for MoreInfo:

public class MoreInfo
{
        public string Name { get; set; }
        public string selectedCheckboxItems {get; set;}
}

我想知道如何在视图中创建一个复选框列表并通过核对项目,我的上提交控制器。

I want to know how to create a checkbox list on the view and pass the checked off items to my controller on submit.

我将如何去创造复选框列表,以及如何通过所有的检查项目和处理它们?

How would I go about creating the checkbox list and how to pass all the checked items and process them?

推荐答案

让我们修改模型一点:

public class ItemViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

,那么你可以有一个控制器:

then you could have a controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        // This action is used to render the form => 
        // we should populate our model with some values
        // which could obviously come from some data source
        var model = new[]
        {
            new ItemViewModel { Id = "1", Checked = true, Name = "item 1" },
            new ItemViewModel { Id = "2", Checked = false, Name = "item 2" },
            new ItemViewModel { Id = "3", Checked = true, Name = "item 3" },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<ItemViewModel> items)
    {
        // This action will be invoked when the form is submitted
        // and here the view model will be properly bound and
        // you will get a collection of all items with their
        // corresponding id, name and whether they were checked or not
        ...
    }
}

那么你将有一个相应的视图(〜/查看/主页/ Index.cshtml ),这将包含表单,允许用户检查/取消选中值:

then you would have a corresponding view (~/Views/Home/Index.cshtml) which would contain the form allowing the user to check/uncheck values:

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

和最后编辑模板(〜/查看/主页/ EditorTemplates / ItemViewModel.cshtml

@model AppName.Models.ItemViewModel
// Those two hidden fields are just to persist the id and name
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
    @Html.CheckBoxFor(x => x.Checked)
    @Html.LabelFor(x => x.Checked, Model.Name)
</div>

这篇关于在的CheckBoxList MVC3查看并得到检查项目传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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