5

我正在尝试从复选框列表中检索选中的复选框值,但没有成功,下面是我尝试过的代码:

模型

 [DisplayName("Gender")]
    public IList<SelectListItem> Gender { get; set; }

控制器

 public ActionResult Index()
        {
            AssociateFormViewModel objStudentModel = new AssociateFormViewModel();

            List<SelectListItem> genderNames = new List<SelectListItem>();
            genderNames.Add(new SelectListItem { Text = "Male", Value = "1" });
            genderNames.Add(new SelectListItem { Text = "Female", Value = "2" });
            genderNames.Add(new SelectListItem { Text = "Prefer not to say", Value = "3" });

            objStudentModel.Gender = genderNames;
            return PartialView("AssociateApplicationForm", objStudentModel);

        }

[HttpPost]
        public ActionResult HandleFormSubmit(MembershipFormViewModel model)
        {
            //model not valid, do not save, but return current umbraco page
            if (ModelState.IsValid == false)
            {
                return CurrentUmbracoPage();
            }
 string test = "Gender: " + model.Gender + Environment.NewLine; //getting null here
 return RedirectToCurrentUmbracoPage();
}

看法

@foreach (var names in @Model.Gender)
                {
                var checkBoxId = "chk" + names.Value;
                var tdId = "td" + names.Value;
                    <table width="100%">
                        <tr >
                            <td width="20px">
                                <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />
                            </td>
                            <td id="@tdId"  width="100px">
                                @names.Text
                            </td>
                        </tr>
                    </table>

}

任何我弄错的想法,选中的复选框值在发布操作中为空,另外,我如何限制用户只选择一个复选框,

任何帮助或建议将不胜感激。谢谢

4

2 回答 2

11

为您的复选框指定一个名称:

<input name="gender" type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />

然后接受带有参数名称的字符串数组gender

[HttpPost]
        public ActionResult HandleFormSubmit(string[] gender,
             MembershipFormViewModel model)
        {
            //model not valid, do not save, but return current umbraco page
            if (ModelState.IsValid == false)
            {
                return CurrentUmbracoPage();
            }
            string test = "Gender: " + model.Gender + Environment.NewLine; //getting null here
            return RedirectToCurrentUmbracoPage();
        }
于 2013-11-11T13:48:04.433 回答
2

根据您的代码model.Gender是一个仅用于创建复选框的列表。要获取选定的复选框值,您应该在模型中添加一个新属性,例如

public string SelectedGender { get; set; }

并在创建复选框时将复选框命名为新的属性名,即 SelectedGender

<input type="checkbox" id="SelectedGender1" name="SelectedGender" class="chkclass" value="@names.Value" />

希望这会帮助你。

于 2013-11-11T13:20:50.377 回答