Cant figure out why I don’t receive object in controller. I followed example from here: http://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example
Mine looks like this:
CONTROLLER
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);
}
MODEL
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>
After selecting changes in the list and pressing submit button
public ActionResult Users2(UserProfile user)
user is empty. Tried using hidden field for each property of UserProfile but no change in behaviour.
In your view you need to wrap form around all the properties from the model. Cause when you submit the form, it only gets ListBox values and that does not match to your UserProfile object. So do something like that:
Make sure at least HiddenFor elements are inside of the form. DisplayFor would not make much difference. Also do include RoleId as a hidden in the form.
I could not be correct about what exact elements you need to put inside your form, but your problems lies in that area – submitted form does not have enough information to map it to an object.