无法弄清楚为什么我没有在控制器中收到对象。我从这里跟随示例:http ://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example
我的看起来像这样:
控制器
private List<webpages_Roles> GetOptions()
{
List<webpages_Roles> categories = new List<webpages_Roles>();
foreach (Models.webpages_Roles databaseRole in Securitydb.webpages_Roles.ToArray())
{
categories.Add(new webpages_Roles() { RoleName = databaseRole.RoleName, RoleId = databaseRole.RoleId });
}
return categories;
}
public ActionResult Users2()
{
UserProfile user = new UserProfile();
user.UserId = 24;
user.UserName = "Alan";
user.webpages_Roles.Add(new webpages_Roles { RoleName = "Administrator", RoleId = 1 });
ViewBag.Categories = GetOptions();
return View(user);
}
[HttpPost]
public ActionResult Users2(UserProfile user)
{
ViewBag.Categories = GetOptions();
return View(user);
}
模型
public partial class webpages_Roles
{
public webpages_Roles()
{
this.UserProfiles = new HashSet<UserProfile>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
}
public partial class UserProfile
{
public UserProfile()
{
this.webpages_Roles = new HashSet<webpages_Roles>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
}
看法
@model Models.UserProfile
@{
ViewBag.Title = "Users2";
}
<div>
<h1>Select Values</h1>
<ul>
@foreach (Models.webpages_Roles c in Model.webpages_Roles)
{
<li> @c.RoleId </li>
}
</ul>
@Html.DisplayForModel()
@Html.HiddenFor(x => x.webpages_Roles)
<h1>Change Values</h1>
@using (Html.BeginForm())
{
@Html.ListBoxFor(x => x.webpages_Roles, new MultiSelectList(ViewBag.Categories, "RoleId", "RoleName", Model.webpages_Roles));
<br />
<input type="submit" value="Submit" />
}
</div>
在列表中选择更改并按下提交按钮后
public ActionResult Users2(UserProfile user)
用户为空。尝试对 UserProfile 的每个属性使用隐藏字段,但行为没有改变。