c# - 如何将复选框映射到 MVC 模型成员?

标签 c# .net asp.net-mvc iis model

我有一个 MVC View

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

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

<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 />

我有一个 Controller - Action 对

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

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

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

最佳答案

好的,这个将用于 MVC3,但是 - 除了语法更改 - 也应该在 MVC2 中工作。方法基本相同。

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

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

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

然后将此模型传递给显示的 View ( 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 等)允许将数据绑定(bind)到模型属性。

请注意,当属性的类型为 bool 时,EditorFor 也会在 View 中为您提供复选框。 :)

然后,当您提交给 Controller 时,它会自动绑定(bind)值:

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

关于c# - 如何将复选框映射到 MVC 模型成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649454/

相关文章:

c# - 覆盖 XML 反序列化以使用基本反序列化并添加功能

c# - Lambda 表达式编译(== 和 equal with char)

C# - 在运行时将文件作为资源添加到我的 Exe

c# - 如何通过 WCF 服务发送 IList?

c# - 为什么我的编码在解码后添加\0?

c# 在日期范围之间退款

c# - 如何用表达式参数实现方法c#

asp.net-mvc - 为什么从 razor View 执行的 C# 代码会被编码?

asp.net-mvc - 如何更改 jslint(VS 2010 扩展名)以忽略文件?

c# - 如何使用 http 请求调用 ApiController 中的方法?