我收到的错误消息是:
System.Web.Mvc.dll中发生了'System.InvalidOperationException'类型的异常,但未在用户代码中处理
其他信息:模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。
这是特定的DropDownListFor:
@Html.DropDownListFor(model => new SelectList(model.DropDownList), Model.DropDownList, new { id = "SelectedCompanyId" })
以下是视图模型:
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { 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")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public SelectList DropDownList { get; set; }
public int SelectedCompanyId { get; set; }
}
以下是模型:
public class ApplicationUser : IdentityUser
{
public virtual Company Company { get; set; }
public int CompanyId { get; set; }
}
最后这是控制器
[AllowAnonymous]
public ActionResult Register()
{
var list = new List<SelectListItem>();
using (var db = new PortalDbContext())
{
list = db.Companys.ToList().Select(x => new SelectListItem {Text = x.Name, Value = x.Id.ToString()}).ToList();
}
var returnList = new SelectList(list);
var model = new RegisterViewModel() { DropDownList = returnList };
return View(model);
}
答案 0 :(得分:2)
lambda表达式应该选择模型的成员来存储值。new SelectList(model.DropDownList)
不是模型的成员。
如果您要存储值的成员是SelectedCompanyId
,那么
@Html.DropDownListFor(m => m.SelectedCompanyId, Model.DropDownList)