如果您有一组复选框,请像这样创建一个 ViewModel
public class ExpertiseCodeViewModel
{
public string Name { set;get;}
public int ExpertiseId { set;get;}
public bool IsSelected { set;get;}
}
现在在您的主 ViewModel 中,将其集合添加为属性
public class UserViewModel
{
public List<ExpertiseCodeViewModel > Expertises{ set; get; }
public UserViewModel()
{
if(this.Expertises==null)
this.Expertises=new List<ExpertiseCodeViewModel>();
}
}
并在您创建一个名为 ExpertiseCodeViewModel 的编辑器模板
@model ExpertiseCodeViewModel
@Html.CheckBoxFor(x => x.IsSelected)
@Html.LabelFor(x => x.IsSelected, Model.Name)
@Html.HiddenFor(x => x.ExpertiseId )
将此包含在您的主视图中
@model UserViewModel
@using (Html.BeginForm())
{
//other elements
@Html.EditorFor(m=>m.Expertises)
<input type="submit" value="Save" />
}
在您的 HTTPPost Action 方法中,
[HttpPost]
public ActionResult Save(UserViewModel model)
{
List<int> items=new List<int>();
foreach (ExpertiseCodeViewModel objItem in model.Expertises)
{
if (objPVM.IsSelected)
{
//you can get the selected item id here
items.Add(objItem.ExpertiseId);
}
}
}