I have a SelectList which functions perfectly, unless the model is is passed back to the View again (eg when the model is invalid). When it is passed back I get the error below. What am I missing?
Line that throws an InvalidOperationException:
@Html.DropDownListFor(m => m.companyId, Model.CompanyList, "SELECT COMPANY")
I tried:
if g.companyId = null;
commented out:
InvalidOperationException: The ViewData item that has the key 'companyId' is of type 'System.String' but must be of type 'IEnumerable'.
if g.companyId = null;
is not commented out:
InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'companyId'.
controller
[HttpPost]
public ActionResult GCLandingAddUser(GUser g)
{
//will not accept if phone is same as email and sanitize text inputs
if (!g.isValid()) {
g.companyId = null;
return View("AddGCLUser", g);
}
}
public ActionResult GCLandingAddUser()
{
GUser g=new GUser();
g.companyList=GetSelectList();
return View("AddGCLUser",g);
}
Model
public class GUser
{
[Required(ErrorMessage = "company is required")]
[Display(Name = "company id")]
public string companyId { get; set; }
public List<SelectListItem> GetSelectList(){
var GroupList = new List<SelectListItem>();
GroupList.Add(new SelectListItem{Text="1",Value="1"});
GroupList.Add(new SelectListItem{Text="2",Value="2"});
return GroupList;
}
public bool isValid(){return false;}//guarantees it will be passed back
}
View (GCLandingAddUser.cshtml)
@model GUser
@using (@Html.BeginForm())
{
<div class="panel-body" id="MyDiv">
<div>
@Html.LabelFor(m => m.companyId)
@Html.DropDownListFor(m => m.companyId, Model.CompanyList, "SELECT COMPANY")
@Html.ValidationMessageFor(m => m.companyId)
</div>
</div>
<input type="submit" value="Submit" />
}