我如何绑定到一个列表中MVC 3剃须刀在模型的属性? [英] How do I bind to a List as a Property on a Model in MVC 3 Razor?
本文介绍了我如何绑定到一个列表中MVC 3剃须刀在模型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,它看起来是这样的:
I've got a model that looks something like this:
public class EditUserViewModel
{
public EditUserViewModel()
{
}
public EditUserDataModel User { get; set; }
}
通过一个支持对象,看起来像这样:
With a backing object that looks like this:
public class EditUserDataModel
{
public EditUserDataModel()
{
Roles = new List<UserRoleListDataModel>();
}
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Full Name")]
public string FullName { get { return FirstName + " " + LastName; } }
public List<UserRoleListDataModel> Roles { get; set; }
}
和UserRoleListDataModel看起来是这样的:
And UserRoleListDataModel looks like this:
public class UserRoleListDataModel
{
public Guid Id { get; set; }
public string RoleName { get; set; }
public bool UserIsInRole { get; set; }
}
然后,在我的剃须刀文件,我使用的是整个事情像这样:
Then, in my Razor file, I am using the whole thing like so:
@foreach (var role in Model.User.Roles)
{
<tr>
<td>@role.RoleName</td>
<td>@Html.CheckBoxFor(x=>role.UserIsInRole)</td>
</tr>
}
我遇到的问题是,当我提交表单,打我的控制器动作,角色列表将不会填充到我的新模式。
The problem I'm having, is when I submit the form and hit my controller action, the Roles list is not populated on my new model.
下面是在控制器看起来像提交操作:
Here is what the submit action on the controller looks like:
public ActionResult EditUser(EditUserViewModel model) // model.User.Roles is empty.
{
// Do some stuff...
return RedirectToAction("UserList");
}
任何人有什么建议吗?
Anyone have any suggestions?
推荐答案
克里斯卡鲁接近,并让我在正确的轨道上。
Cris Carew was close, and got me on the right track.
@for (int i=0;i < Model.User.Roles.Count;i++)
{
@Html.Hidden("User.Roles.Index", i)
@Html.HiddenFor(x => x.User.Roles[i].RoleName)
<tr>
<td>@Html.DisplayFor(x => Model.User.Roles[i].RoleName)</td>
<td>@Html.CheckBoxFor(x => Model.User.Roles[i].UserIsInRole)</td>
</tr>
}
这篇关于我如何绑定到一个列表中MVC 3剃须刀在模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文