我有一个“ ViewModel”的工作示例,我认为它将适用于下拉列表。目前,我正在使用它来执行Foreach,它可以正常工作,但是在表单上需要一个相同的结果。我尝试了一些我认为可能有用的想法。似乎没有人能做到。我没有示例,因为我通常只阅读一堆帖子,然后开始向其投掷代码以查看问题所在。我仍在学习,因此希望有人可以向我指出正确的方向,或者向我展示一些可以填充我所需内容的代码。我相信我的ViewModel中有我需要的所有东西,我想远离Viewbag。下面是我的“ ViewModel”。
除非有更好的方法,否则这是我要用来填充下拉菜单的行。
result.Addresses = db.Addresses.Where(a => a.CompanyId == result.CompanyId);
编辑-这是此'ViewModel'的当前可用下拉列表
@Html.DropDownList("AddressId", new SelectList(Model.Addresses, "AddressId", "LocationName"), "Select Address user belongs to", new { @class = "form-control" })
这是整个“ ViewModel”
public class RegisterUserViewModel
{
public static RegisterUserViewModel GetCompanyId(string userId, CustomerEntities db)
{
var qCust = from ad in db.Addresses
join anu in db.Users on ad.AddressId equals anu.AddressId
join cus in db.CompanyNames on ad.CompanyId equals cus.CompanyId
where (anu.Id == userId)
select new RegisterUserViewModel()
{
UserId = userId,
CompanyId = cus.CompanyId,
AddressId = ad.AddressId
};
var result = qCust.SingleOrDefault();
if (result != null)
{
result.Addresses = db.Addresses.Where(a => a.CompanyId == result.CompanyId);
};
return result;
}
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "User Address")]
public int AddressId { get; set; }
[Required]
[Display(Name = "User Roles")]
public string UserRoles { get; set; }
public string UserId { get; set; }
public int CompanyId { get; set; }
public virtual IEnumerable<Addresses> Addresses { get; set; }
}
我希望将AddressId作为值,将LocationName作为文本。
答案 0 :(得分:2)
尝试如下。
@Html.DropDownList("address", new SelectList(Model.Addresses, "AddressId", "LocationName"))
正如您在评论中提到的那样,使用@Html.DropDownList(model => model.AddressId...
后,您将获得第二项作为选定值,所以这里发生的是它将自动设置model.AddressId
中的选定值。只是检查一下。
现在,如果要设置默认值,请确保model.AddressId
的值与默认选择值相同。