MVC复选框返回null

时间:2012-03-02 15:19:55

标签: asp.net-mvc razor

我有一个复选框,但表单正在提交,勾选的值未被提交...

HTML:

@foreach (var radiobutton in Model.InterestedIn)
           {
             <span >  @Html.CheckBox("selected", radiobutton)
               <label>@radiobutton</label></span>
               <br />
           } 

型号:

[Display(Name = "Would you be interested in receiving *")]
        public IList<string> InterestedIn { get; set; }

控制器:

IList<string> lists = new List<string>();
            lists.Insert(0, "Latest News");
            lists.Insert(1, "Special Offers");
            lists.Insert(1, "New Products");
            model.InterestedIn = lists;

的PostMethod:

[HttpPost]
        public ActionResult Index(Competition model)
        {
            if (ModelState.IsValid)
            {

1 个答案:

答案 0 :(得分:0)

我不认为你的代码会编译。 CheckBox帮助器需要一个布尔值作为第二个参数,而你传递的是一个字符串。

试试这样:

@model MyViewModel

@using (Html.BeginForm())
{
    foreach (var value in Model.InterestedIn)
    {
        <span>
            <input type="checkbox" name="interestedin" value="@Html.AttributeEncode(value)" />
            <label>@value</label>
        </span>
        <br />
    } 
    <button type="submit">OK</button>
}

这假定您具有以下视图模型:

public class MyViewModel
{
    [Display(Name = "Would you be interested in receiving *")]
    public IList<string> InterestedIn { get; set; }
}

和以下控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        IList<string> lists = new List<string>();
        lists.Insert(0, "Latest News");
        lists.Insert(1, "Special Offers");
        lists.Insert(1, "New Products");
        var model = new MyViewModel();
        model.InterestedIn = lists;
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

如果您想使用CheckBox甚至更好的CheckBoxFor帮助器,则必须调整视图模型,使其不再具有IList<string>属性,而是{{1其中IList<CheckBoxItemViewModel>是另一个包含标签的视图模型,以及一个boolean属性,指示是否已选择此值。