0
votes

The error message I'm receiving is:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Here is the specific DropDownListFor:

@Html.DropDownListFor(model => new SelectList(model.DropDownList), Model.DropDownList, new { id = "SelectedCompanyId" })

Here is the View Model:

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

Here is the Model:

public class ApplicationUser : IdentityUser
    {
        public virtual Company Company { get; set; }
        public int CompanyId { get; set; }
    }

And finally here is the controller

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

1 Answers

2
votes

The lambda expression is supposed to select a member of the model to store the value in. new SelectList(model.DropDownList) is not a member of the model.

If the member you want to store the value in is SelectedCompanyId, then

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