编辑:删除部分视图以简化操作。现在我只需要找出为什么视图没有发布值
ViewModelProspectUsers
public class ViewModelProspectUsers
{
public int Id { get; set; }
public string User { get; set; }
public IEnumerable<ViewModelProspectSelect> Prospects { get; set; }
}
ViewModelProspectSelect
public class ViewModelProspectSelect
{
public int ProspectID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
查看
@model OG.ModelView.ViewModelProspectUsers
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.Id)
<h5>Please Select Prospects you wish to assign to this User.</h5>
----- HERE是以前的部分,这些值未发布到[Post]
方法 ------
-----------------------------------------但是他们填充得很好----------------------------------------
@foreach (var item in Model.Prospects)
{
@Html.HiddenFor(x => item.ProspectID)
@Html.DisplayFor(x => item.Name)
@Html.EditorFor(x => item.IsSelected)
}
@*@Html.Partial("_ShowProspectCheckedForUser", Model.Prospects)*@
@*@Html.Partial("_ShowProspectCheckedForuser", new OG.ModelView.ViewModelProspectSelect())*@
<input type="submit" value="Save changes" />
@Html.ActionLink("Cancel", "Index")
}
发布
[HttpPost]
public ActionResult UsersInProspect(ViewModelProspectUsers viewModel)
如果我要查看viewModel.Prospects(m=>m.isSelected)
//&lt; - 此值为Null不应该
我的viewmodel Variable显示数据,但不显示Ienumerable。
答案 0 :(得分:1)
处理列表类型对象时,必须使用数组表示法引用它们,以便以模型绑定器可以解析它们的方式生成字段名称,即:
for (var i = 0; i < Model.Count(); i++)
{
@Html.LabelFor(m => Model[i].SomeProperty)
@Html.EditorFor(m => Model[i].SomeProperty)
}
在您的方案中,您可以更好地使用视图模型来包含列表并向项目添加Selected
属性,以便您可以跟踪哪些属性已被选中。
public class ViewModelProspects
{
public List<ViewModelProspectSelect> Prospects { get; set; }
}
public class ViewModelProspectSelect
{
// Whatever else you have
public bool Selected { get; set; }
}
然后,在您看来:
@model ViewModelProspects
@using (Html.BeginForm())
{
for (var i = 0; i < Model.Prospects.Count(); i++)
{
<label>
@Html.HiddenFor(m => Model.Prospects[i].Id)
@Html.CheckboxFor(m => Model.Prospects[i].Selected, true)
@Model.Prospects[i].Name
</label>
}
}
最后,更改您的操作方法签名:
[HttpPost]
public ActionResult UsersInProspect(ViewModelProspects model)
然后,您可以使用以下命令轻松获取操作中所选ID的列表:
var selectedIds = model.Prospects.Where(m => m.Selected).Select(m => m.Id)