i'm working with custom authentication with asp.net mvc , i'm using Role Provider. i have many to many relation User , Role , UserInRoles . the error in binding roles values in checkboxs in view
i tried debugging controller create method it return all data in Role table then continue to view in foreach
error DataBinding: 'System.String' does not contain a property with the name 'Name'.
User Model
public class User
{
[Key]
public string UserId { get; set; }
public string Name { get; set; }
public virtual ICollection<UserInRoles> UserInRoles { get; set; }
}
Role Model
public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<UserInRoles> UserInRoles { get; set; }
}
UserInRole Model
public class UserInRoles
{
[Key, Column(Order = 0)]
public string UserId { get; set; }
[Key, Column(Order = 1)]
public int RoleId { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
Controller
public ActionResult Create()
{
ViewBag.RoleId = new SelectList(Roles.GetAllRoles().ToList(), "Name", "Name");
return View();
}
View
@model AramexOneKnowledge.Models.RegisterViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Select User Role
</label>
<div class="col-md-10">
@foreach (var item in (SelectList)ViewBag.RoleId)
{
<input type="checkbox" name="SelectedRoles"
value="@item.Value" class="checkbox-inline" />
@Html.Label(item.Value, new { @class = "control-label" })
}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
expected result display roles in checkbox
this exception because Roles.GetAllRoles()
returns string[]
and you try to bind property Name
inside it which it not exists.
so to overcome this issue you can populate you checkbox list as following
ViewBag.RoleId = Roles.GetAllRoles().Select(r => new SelectListItem{Text = r, Value = r});
in this case you SelectListItem
Value
and Text
it will be the role name for both of them