I'm brand new to MVC on the ASP.NET platform and I'm having an issue with trying to create an Html form that uses a drop down list as one of the options. I've successfully been able to use the form when the drop down list isn't using it's default value. But, I've been doing some testing and when I leave the drop down list empty it throws a couple of errors.
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'CraigRole'.
The code that I am using.
Controller:
public ActionResult Create()
{
List<SelectListItem> items = new List<SelectListItem>();
SelectListItem item1 = new SelectListItem() { Value = "User", Text = "User" };
items.Add(item1);
SelectListItem item2 = new SelectListItem() { Value = "Admin", Text = "Admin" };
items.Add(item2);
SelectListItem item3 = new SelectListItem() { Value = "Super Admin", Text = "SuperAdmin" };
items.Add(item3);
ViewData["CraigRole"] = items;
return View();
}
View:
<div class="form-group">
@Html.LabelFor(model => model.CraigRole, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CraigRole, (List<SelectListItem>)ViewData["CraigRole"], "--- Please Select ---", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CraigRole, "", new { @class = "text-danger" })
</div>
</div>
I have never had experience with Validation in MVC, so I apologize if I am missing something. I also would like to point out that I have seen many questions regarding drop down lists on stack exchance (that is how I've gotten this far), but I can't find a solution for this problem. Any help is appreciated!.