对了,伙计们。我需要你的智慧,因为我找不到正确的方法。
我有一个视图模型:
public class EditUserViewModel
{
public User User;
public IQueryable<ServiceLicense> ServiceLicenses;
}
用户并不重要,因为我知道如何处理它。
ServiceLicenses 具有以下实现:
public class ServiceLicense
{
public Guid ServiceId { get; set; }
public string ServiceName { get; set; }
public bool GotLic { get; set; }
}
获取已检查的用户列表很酷。它就像一个魅力。
<fieldset>
<legend>Licenses</legend>
@foreach (var service in Model.ServiceLicenses)
{
<p>
@Html.CheckBoxFor(x => service.GotLic)
@service.ServiceName
</p>
}
</fieldset>
我遇到的问题是将更新后的 ServiceLicenses 对象与新检查的服务返回到我的控制器中的 HttpPost 。为了简单起见,我们可以说它看起来像这样:
[HttpPost]
public ActionResult EditUser(Guid id, FormCollection collection)
{
var userModel = new EditUserViewModel(id);
if (TryUpdateModel(userModel))
{
//This is fine and I know what to do with this
var editUser = userModel.User;
//This does not update
var serviceLicenses = userModel.ServiceLicenses;
return RedirectToAction("Details", new { id = editUser.ClientId });
}
else
{
return View(userModel);
}
}
我知道我使用 CheckBox 的方式是错误的。我需要更改什么才能更新服务许可证并在表单中选中复选框?
我知道 ServiceLicenses 属性是一个集合,您希望 MVC 绑定器将其绑定到您的操作参数属性。为此,您应该在视图中附加带有输入的索引,例如
<input type="checkbox" name = "ServiceLicenses[0].GotLic" value="true"/>
<input type="checkbox" name = "ServiceLicenses[1].GotLic" value="true"/>
<input type="checkbox" name = "ServiceLicenses[2].GotLic" value="true"/>
前缀可能不是强制性的,但在绑定操作方法参数的集合属性时非常方便。为此,我建议使用 for 循环而不是 foreach 并使用 Html.CheckBox helper 而不是 Html.CheckBoxFor
<fieldset>
<legend>Licenses</legend>
@for (int i=0;i<Model.ServiceLicenses.Count;i++)
{
<p>
@Html.CheckBox("ServiceLicenses["+i+"].GotLic",ServiceLicenses[i].GotLic)
@Html.CheckBox("ServiceLicenses["+i+"].ServiceName",ServiceLicenses[i].ServiceName)//you would want to bind name of service in case model is invalid you can pass on same model to view
@service.ServiceName
</p>
}
</fieldset>
不使用强类型助手只是个人偏好。如果你不想像这样索引你的输入,你也可以看看这个很棒的post http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/通过史蒂夫·森德森
Edit: i have blogged http://zahidadeel.blogspot.com/2011/05/master-detail-form-in-aspnet-mvc-3-i.html关于在 ASP.NET MVC3 上创建主详细信息表单,这也与列表绑定相关。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)