0

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

That makes more sense, but the one thing that confuses me is both drop downs show System.Web.Mvc.SelectListItem and then when I try and register it says "The field SelectedCompanyId must be a number."
That's because it needs to be var returnList = new SelectList(db.Companys, "Id", "Name"); Remove the first 5 lines from Register() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.