不能弄清楚爲什麼我沒有收到控制器中的對象。我跟着從這裏例如:http://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example爲什麼mvc無法通過對象
礦看起來像這樣:
控制器
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; }
}
VIEW
@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的每個屬性使用隱藏字段,但行爲不變。
的StackOverflow是不是一個人羣來源的調試服務。 –
@tereško有時我覺得這是服務! – trailmax