i,实际上想要显示角色名称来代替角色ID 所以我这样做 这些是我的模特
[Table("User")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required(ErrorMessage = "Please Provide Fullname", AllowEmptyStrings = false)]
[Display(Name = "Full Name")]
public string Full_Name { get; set; }
[Required(ErrorMessage = "Please Provide Username", AllowEmptyStrings = false)]
public string Username { get; set; }
[Required(ErrorMessage = "Please provide password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Please Select User type", AllowEmptyStrings = false)]
[Display(Name = "USER TYPE")]
public int ROLEID { get; set; }
[Required(ErrorMessage = "Please Select Login Status", AllowEmptyStrings = false)]
[Display(Name = "Login Status")]
public string Login_Status { get; set; }
public List<Role> role { get; set; }
UserDB db = new UserDB();
public Role getname(int id) {
return db.roles.SingleOrDefault(d => d.ROLEID == id);
}
}
[Table("ROLE")]
public class Role
{
public int ROLEID { get; set; }
public string ROLENAME { get; set; }
}
public class UserRole
{
public List<User> Ruser { get; set; }
public List<Role> Rrole { get; set; }
}
这是我的控制器
public ActionResult Userlist(int? page)
{
UserDB dc = new UserDB();
List<User> users = dc.users.ToList();
UserRole userrole = new UserRole();
userrole.Ruser = users;
return View(userrole);
}
这是我的观点
@model PHARMACY.Models.UserRole
<table class="table table-striped table-hover ">
<tr>
<th>
@Html.DisplayNameFor(model => model.Ruser.First().Full_Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Ruser.First().Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Ruser.First().Password)
</th>
<th>
@Html.DisplayNameFor(model => model.Rrole.First().ROLENAME)
</th>
<th>
@Html.DisplayNameFor(model => model.Ruser.First().Login_Status)
</th>
<th></th>
</tr>
@foreach (var item in Model.Ruser) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Full_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Username)
</td>
<td>
@Html.DisplayFor(modelItem => item.Password)
</td>
<td>
@{
var name = Model.Rrole.Where(i => i.ROLEID == item.ROLEID);
@Html.DisplayFor(m => m.Rrole.Where(i => i.ROLEID == item.ROLEID).FirstOrDefault());
}
</td>
<td>
@Html.DisplayFor(modelItem => item.Login_Status)
</td>
<td>
<p class="label label-info">@Html.ActionLink("Edit", "EditUser", new { id=item.UserId,})</p> |
<p class="label label-danger">@Html.ActionLink("Delete", "DeleteUser", new { id=item.UserId })</p>
</td>
</tr>
}
</table>
但它通过错误“值不能为空。 参数名称:source“
答案 0 :(得分:0)
如果您的数据库中没有用户,此行将导致错误:
@Html.DisplayNameFor(model => model.Ruser.First().Full_Name)
您没有处理model.Ruser
为空的情况。