【问题标题】:Exception using @Html.DropDownListFor使用 @Html.DropDownListFor 的异常
【发布时间】:2015-02-13 23:37:26
【问题描述】:

我收到的错误信息是:

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);
    }

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    lambda 表达式应该选择模型的一个成员来存储值。new SelectList(model.DropDownList) 不是模型的成员。

    如果你要存储值的成员是SelectedCompanyId,那么

    @Html.DropDownListFor(m => m.SelectedCompanyId, Model.DropDownList)
    

    【讨论】:

    • 这更有意义,但让我感到困惑的一件事是两个下拉菜单都显示 System.Web.Mvc.SelectListItem 然后当我尝试注册它时说“字段 SelectedCompanyId 必须是一个数字。 "
    • 那是因为需要var returnList = new SelectList(db.Companys, "Id", "Name");Register()方法的前5行去掉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多