我在这里可能是个白痴,但在获取是否已选中/未选中复选框的值方面遇到问题。这是到目前为止我得到的:
I'm probably a idiot here but I'm having problems getting the value of whether or not a checkbox is checked/selected or not. Here's what I've got so far:
在我的模型中:
public IEnumerable<SelectListItem> Insurers { get { var list = new List<SelectListItem>(); string zInsurersList = "Age UK,Be Wiser,Call Connection,Churchill,Sainsbury's,Direct Line,Hastings Direct,LV=,Nationwide,RIAS,Swinton"; string[] zInsurers = zInsurersList.Split(','); foreach (string aInsurer in zInsurers) { list.Add(new SelectListItem() { Text = aInsurer, Value = aInsurer, Selected=false}); } return list; } } }我的观点:
@foreach (var insurer in @Model.Insurers) { var zInsurer = insurer.Text; var zValue = insurer.Value; <tr> <td style="width: 120px; height: 35px;"><span id="@zInsurer">@zInsurer</span></td> <td style="width: 40px; height: 35px;"><input id="@zInsurer" type="checkbox" name="@zInsurer"></td> </tr> }所以在我的控制器中,我试图循环列表并获取值用户是否选择了以下选项:
So in my controller I'm trying to loop the list and get the value of whether or not the user has selected the option:
foreach (var item in model.Insurers) { //if (item.GetType() == typeof(CheckBox)) //string controlVal = ((SelectListItem)item).Selected.ToString(); zInsurers = zInsurers + item.Text + " " + ((SelectListItem)item).Selected.ToString() + "<br/>"; }但该值始终返回false。
But the value always returns false.
有人可以花点时间强调我的愚蠢吗?
Could someone spare a few mins to highlight my stupidity please?
谢谢
Craig
推荐答案有很多方法可以做到这一点。我通常在模型中添加 String Array 来收集选定的值。
There are a lot of ways to do it. I normally add String Array in model to collect selected values.
public string[] SelectedInsurers { get; set; } <input type="checkbox" name="SelectedInsurers" value="@insurer.Value" />这是示例代码-
public class MyModel { public string[] SelectedInsurers { get; set; } public IEnumerable<SelectListItem> Insurers { get { var list = new List<SelectListItem>(); string zInsurersList = "Age UK,Be Wiser,Call Connection,Churchill,Sainsbury's,Direct Line,Hastings Direct,LV=,Nationwide,RIAS,Swinton"; string[] zInsurers = zInsurersList.Split(','); foreach (string aInsurer in zInsurers) { list.Add(new SelectListItem { Text = aInsurer, Value = aInsurer, Selected = false }); } return list; } } }操作方法
Action Methods
public ActionResult Index() { return View(new MyModel()); } [HttpPost] public ActionResult Index(MyModel model) { return View(); }查看
View
@using (Html.BeginForm()) { foreach (var insurer in @Model.Insurers) { <input type="checkbox" name="SelectedInsurers" value="@insurer.Value" /> @insurer.Text<br/> } <input type="submit" value="Post Back" /> }结果
Result
更多推荐
MVC控制器获得“复选框列表”的值
发布评论