如何将复选框映射到 MVC 模型成员? [英] How do I map checkboxes onto MVC model members?

查看:15
本文介绍了如何将复选框映射到 MVC 模型成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MVC 视图

I have an MVC view

<%@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPage<ModelData>" %>

我有一个带有 HTML 标记的表单,用于一组复选框:

and I have a form with HTML markup for a set of checkboxes:

<label for="MyCheckbox">Your choice</label>
<input type="checkbox" id="Option1" class="checkbox" name="MyCheckbox" value="Option one" />
<label for="Option1">Option one</label><br />
<input type="checkbox" id="Option2" class="checkbox" name="MyCheckbox" value="Option two" />
<label for="Option2">Option two</label><br />

我有一个控制器-动作对

and I have a controller-action pair

class MyController : Controller {
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult RequestStuff( ModelData data )
    {
    }
}

并且在提交表单时调用该操作.

and that action is invoked when the form is submitted.

如何将复选框映射到 ModelData 的成员(以及我必须添加到 ModelData 的成员),以便在提交表单时 data 存储有关哪些复选框被选中的信息?

How do I map the checkboxes onto members of ModelData (and what members I have to add to ModelData) so that when the form is submitted data stores information on which checkboxes are checked?

推荐答案

好的,这将适用于 MVC3,但是 - 除了语法更改之外 - 也应该适用于 MVC2.方法基本相同.

OK, this one will be for MVC3, but - save for syntax changes - should work in MVC2 too. The approach is essentially the same.

首先,你应该准备一个合适的(视图)模型

First of all, you should prepare an appropriate (view)model

public class MyViewModel
{
    [DisplayName("Option 1")]
    public bool Option1 { get; set; }

    [DisplayName("Option 2")]
    public bool Option2 { get; set; }
}

然后您将此模型传递给您正在显示的视图(控制器):

Then you pass this model to the view you're showing (controller):

public ActionResult EditMyForm()
{
    var viewModel = new MyViewModel()
    return View(viewModel);
}

形式:

@model MyViewModel
@using( Html.BeginForm())
{
    @Html.Label("Your choice")

    @Html.LabelFor(model => model.Option1) // here the 'LabelFor' will show you the name you set with DisplayName attribute
    @Html.CheckBoxFor(model => model.Option1)

    @Html.LabelFor(model => model.Option2)
    @Html.CheckBoxFor(model => model.Option2)
    <p>
        <input type="submit" value="Submit"/>
    </p>
}

现在这里的 HTML 帮助程序(所有 CheckBoxForLabelForEditorFor 等)允许将数据绑定到模型属性.

Now here the HTML helpers (all the CheckBoxFor, LabelFor, EditorFor etc) allow to bind the data to the model properties.

现在请注意,当属性为 bool 类型时,EditorFor 也会在视图中为您提供复选框.:)

Now mind you, an EditorFor when the property is of type bool will give you the check-box in the view, too. :)

然后,当您提交给控制器时,它会自动绑定值:

And then, when you submit to the controller, it will auto-bind the values:

[HttpPost]
public ActionResult EditMyForm(MyViewModel viewModel)
{
    //And here the view model's items will be set to true/false, depending what you checked.
}

这篇关于如何将复选框映射到 MVC 模型成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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