加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:38:44 所属栏目:百科 来源:网络整理
导读:我有一个MVC视图 %@ Page Language="C#" MasterPageFile="PathToMaster" Inherits="System.Web.Mvc.ViewPageModelData" % 我有一个HTML标记的表单,用于一组复选框: label for="MyCheckbox"Your choice/labelinput type="checkbox" id="Option1" class="chec
我有一个MVC视图
<%@ 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 />

我有一个控制器动作对

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

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

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

解决方法

好的,这个是MVC3,但是 – 保存语法更改 – 也应该在MVC2中工作.这种做法基本上是一样的.

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

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

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

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

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帮助者(所有的CheckBoxFor,LabelFor,EditorFor等)允许将数据绑定到模型属性.

现在介意你,一个编辑器当属性是bool类型将给你在视图中的复选框.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读