我在 .NET 4.5 上有一个 ASP.NET MVC 页面。
这是我的代码 - 模型类:
public class UserDetail
{
public Int64 UserID { get; set; }
[Required]
[EmailAddress]
public string LoginID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public bool Status { get; set; } = true;
public DateTime LastLoginTime { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
// Columns for Mapping
[Range(1,int.MaxValue, ErrorMessage = "Select a Valid Group Value")]
public int GroupID { get; set; }
public string Group { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Select a Valid Role Value")]
public int RoleID { get; set; }
public string Role { get; set; }
}
public class UserViewModel
{
public UserDetail User { get; set; } = new UserDetail();
public IEnumerable<SelectListItem> Groups { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
查看
@model MyApp.Models.UserViewModel
<label for="ddl_role" class="font-weight-bold">Select Role</label>
@Html.DropDownListFor(x => x.User.RoleID, Model.Roles, "Choose...", new { id = "ddl_role", @class = "form-control form-control-sm" })
控制器动作方法
public ActionResult SomeName()
{
var viewmodel = new UserViewModel();
viewmodel.Groups = Helper.GetSelectListItems(nameof(viewmodel.Groups));
viewmodel.Roles = Helper.GetSelectListItems(nameof(viewmodel.Roles));
viewmodel.User = Helper.GetData();
return View(viewmodel);
}
viewmodel.User = Helper.GetData()
提取UserDetail
对象的数据,viewmodel.Groups
、viewmodel.Roles
都是IEnumerable
的SelectListItem
,它们包含文本和值字段。
但是当我加载视图时,下拉列表始终显示“选择...”作为选定值,即使
Model.User.RoleID
绑定用于反映数据并且 SelectList
也就位,但它不显示选定值通过 Model.User.RoleID
设置
有什么提示我可能会错过什么吗?
您必须根据
User.RoleID
设置所选值。
viewmodel.Roles = Helper.GetSelectListItems(nameof(viewmodel.Roles));
viewmodel.Roles = viewmodel.Roles.Select(item =>
{
item.Selected = (item.Value == viewmodel.User.RoleID.ToString());
return item;
});