我正在尝试获取选定的复选框值
这是我的模型,
public class VehicleViewModel : Vehicle
{
[Display(Name = "Vehicle Type")]
[Required( ErrorMessage = "{0} is required.")]
public string VehicleTypeName { get; set; }
[Display(Name = "Location")]
[Required(ErrorMessage = "{0} is required.")]
public string LocationName { get; set; }
public IEnumerable<AssignProductsViewModel> AssignedProducts { get; set; }
}
public class AssignProductsViewModel
{
public long ProductID { get; set; }
public string ProductName { get; set; }
}
这是我的 Razor View
@foreach (var item in Model.AssignedProducts)
{
<tr>
<td>
<input type="checkbox" value ="@item.ProductID"/>
</td>
<td>
@Html.DisplayFor(model => item.ProductName)
</td>
</tr>
}
这是我的 Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewVehicle(VehicleViewModel vehicleViewModel, string selected)
{
//Do something with the string here
return View();
}
我知道我需要使用 javascript 将选定的复选框值传递给字符串,并将该字符串传递给 Controller 。但我不知道该怎么做,因为我是 javascript 和 MVC 的新手。
最佳答案
根据不需要 ajax post 的评论,您的 AssignProductsViewModel
需要一个附加属性来绑定(bind)复选框
public class AssignProductsViewModel
{
public long ProductID { get; set; }
public string ProductName { get; set; }
public bool IsSelected { get; set; } // add this
}
在 View 中,使用 for
循环或自定义 EditorTemplate
来呈现集合,并使用索引器正确命名控件。 foreach
循环生成重复的 id
(无效 html)和 name
属性(无法绑定(bind)到集合)
@model VehicleViewModel
@using(Html.BeginForm())
{
// controls for VehicleTypeName, LocationName
for(int i = 0; i < Model.AssignedProducts.Count; i++)
{
@Html.HiddenFor(m => m.AssignedProducts[i].ProductID) // ditto for ProductName if you want it on postback
@Html.CheckBoxFor(m => m.AssignedProducts[i].IsSelected)
@Html.LabelFor(m => m.AssignedProducts[i].IsSelected, Model.AssignedProducts[i].ProductName)
}
....
}
并发回
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewVehicle(VehicleViewModel model)
{
// model.AssignedProducts contains the collection with a value indicating if the product has been selected
}
或者,您可以使用 EditorTemplate
作为 AssignProductsViewModel
类型来呈现集合
在/Views/Shared/EditorTemplates/AssignProductsViewModel.cshtml
@model AssignProductsViewModel
@Html.HiddenFor(m => m.ProductID) // ditto for ProductName if you want it on postback
@Html.CheckBoxFor(m => m.IsSelected)
@Html.LabelFor(m => m..IsSelected, Model.ProductName)
在主视图中
@model VehicleViewModel
@using(Html.BeginForm())
{
// controls for VehicleTypeName, LocationName
@Html.EditorFor(m => m.AssignedProducts)
<input type="submit" />
}
关于javascript - 如何获取复选框选定的值并传递给 asp.net mvc 4 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28445867/