如何在 asp.net mvc 4 中获取复选框选定值并传递给控制器

How to get checkbox selected value and pass to controller in asp.net mvc 4

我正在尝试获取选中的复选框值

这是我的模型,

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; }
}

这是我的剃刀观点

@foreach (var item in Model.AssignedProducts)
{
  <tr>
    <td>
      <input type="checkbox" value ="@item.ProductID"/>
    </td>
    <td>
      @Html.DisplayFor(model => item.ProductName)
    </td>
  </tr>
}

这是我的控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewVehicle(VehicleViewModel vehicleViewModel, string selected)
{
  //Do something with the string here
  return View();
}

我知道我需要使用 javascript 将选中的复选框值传递给一个字符串,并将该字符串传递给一个控制器。但我不知道该怎么做,因为我是 javascript 和 MVC 的新手。

根据不需要 ajax post 的评论,您的 AssignProductsViewModel 需要额外的 属性 来绑定复选框

public class AssignProductsViewModel
{
  public long ProductID { get; set; }
  public string ProductName { get; set; }
  public bool IsSelected { get; set; } // add this
}

在视图中,使用 for 循环或自定义 EditorTemplate 呈现集合,并使用索引器正确命名控件。 foreach 循环生成重复的 id(无效 html)和 name 属性(无法绑定到集合)

@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)
  }
  ....
}

和post回到

[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" />
}