Drop-Down Menu Causing Invalid Model State. ASP.NE

2019-07-20 22:09发布

问题:

I have a registration view in my web app. However, account registration would be unsuccessful and my drop-down menu would be outlined in red.

Here is my drop down code:

<div class="editor-label">  
   @Html.LabelFor(model => model.CompanyId, "Company")  
</div>   
<div class="editor-field">  
   @Html.DropDownList("Companies", "<Select Company>")  
</div>

Here is my associated code in the view model:

[Display(Name = "Company")]    
public int? CompanyId { get; set; }

public IEnumerable<SelectListItem> Companies { get; set; }

Here is my associated code in the controller before I return the view:

ViewBag.Companies = new SelectList(db.Companies, "CompanyId", "CompanyName");

As I debug, I find that ModelState.IsValid returns false, and therefore re-returns the view (and re-sets ViewBag.Companies in my case).

How do I complete a successful registration? I do fill out each required field within parameters. It is not required to select company. When I do not select a company, ModelState.IsValid returns true and runs through the code. However, I would like the user to have the option to associate with his company.

Thanks.