I am building a form using ASP.NET MVC which requires a drop-down list populated from a database.
I managed to get the drop-down list appearing, but no matter what I try to get the post data the application throws various errors.
In my Model:
public IEnumerable<SelectListItem> ApplicationTypeList { get; set; }
My Controller Get:
public ActionResult Create()
{
IEnumerable<SelectListItem> ApplicationTypeItems = Lists.ApplicationTypeList.Select(c => new SelectListItem { Value = c.Code, Text = c.Description });
ViewBag.AppTypes = ApplicationTypeItems;
return View();
}
Where c.Code is the value I want when the form is returned (string) and c.Description is just what is displayed.
The HttpPost Controller (auto-generated from scaffolding)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="PaymentID,ApplicationNumber,ApplicantName,ContactEmail,ContactAddress,ContactPhone")] Payment payment)
{
if (ModelState.IsValid)
{
db.Payments.Add(payment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
For whatever reason it did not include ApplicationTypeList in the [Bind(Include=...
I also had to manually added this to the Create.cshtml View:
<div class="form-group">
@Html.LabelFor(model => model.ApplicationTypeList, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ApplicationTypeList", (IEnumerable<SelectListItem>)ViewBag.AppTypes, "Please Select");
@Html.ValidationMessageFor(model => model.ApplicationTypeList)
</div>
</div>
When I submit the form I get the following error on the view:
There is no ViewData item of type 'IEnumerable' that has the key 'ApplicationTypeList'.
I have looked around and tried a couple of other ways of generating the list such as including a new String APplicationTypeCode and creating the list using @Html.DropDownListFor(model => model.ApplicationTypeCode, Model.ApplicationTypeList); but still get errors.
What is the best method of working with a form that includes drop-down lists and returning the selected value to the application?
Thanks.