我正在 MVC 中实现复选框列表,虽然我成功获得了预期的结果,但我对我的方法有疑问:
public class AdditionalServicesModel
{
public IList<SelectListItem> AdditionalServices { get; set; }
}
==================================================== ========================
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
AdditionalServicesModel objAdditionalServicesModel = new AdditionalServicesModel();
List<SelectListItem> services = new List<SelectListItem>();
services.Add(new SelectListItem { Text = "service-1", Value = "1", Selected=false });
services.Add(new SelectListItem { Text = "service-2", Value = "2", Selected=false });
services.Add(new SelectListItem { Text = "service-3", Value = "3", Selected=false });
objAdditionalServicesModel.AdditionalServices = services;
return View(objAdditionalServicesModel);
}
[HttpPost]
public ActionResult Index(AdditionalServicesModel result)
{
return RedirectToAction("Thanks", "Home");
}
public ActionResult Thanks()
{
return View();
}
}
==================================================== ========================
@model checkboxes.Models.AdditionalServicesModel
@{
ViewBag.Title = "Index";
Layout = null;
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
for (int i = 0; i < Model.AdditionalServices.Count; i++)
{
<ul>
<li>
@Html.CheckBoxFor(m=>Model.AdditionalServices[i].Selected, new { id = "Chk-" + i})
@Html.Label(Model.AdditionalServices[i].Text, new { @for = "Chk-" + i })
@Html.HiddenFor(m => Model.AdditionalServices[i].Text)
@Html.HiddenFor(m=> Model.AdditionalServices[i].Value)
</li>
</ul>
}
<input type="submit" value="POST to Controller" />
}
1)对于一个复选框,我应该创建 2 个额外的隐藏字段。有更好的方法吗?我觉得做这么长的路只是为了发送复选框值+名称是错误的,用javascript收集它的值并通过Json发送它会容易得多,但是我不会有一个不显眼的验证......
2)我发送所有复选框,而我只需要发送选定的框。有没有办法通过表单发布来做到这一点?