Jake
Jake

Reputation: 1217

ASP.NET MVC Using DropDownLists

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.

Upvotes: 0

Views: 146

Answers (1)

Krahu
Krahu

Reputation: 183

I suggest create viewmodel

public class InsertPaymentViewModel {
 public SelectList ApplicationTypeList {get; set;}
 // property for selected item
 [Display(Name = "Display name")]
 [Required]
 public int ApplicationTypeSelectedCode {get; set;}
}

In Get action use this model (I don like ViewBag for complex forms)

public ActionResult Create()
{
 var model = new InsertPaymentViewModel();
 model.ApplicationTypeItems = new SelectList(Lists.ApplicationTypeList, "Code", "Description ")
 return View(model);
}

View:

@model PathTo.ViewModels.InsertPaymentViewModel

<div class="form-group">
            @Html.LabelFor(model => model.ApplicationTypeSelectedCode , new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.ApplicationTypeSelectedCode, model.ApplicationTypeItems , "Please Select");
                @Html.ValidationMessageFor(model => model.ApplicationTypeSelectedCode)
            </div>
        </div>

HttpPost action

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(InsertPaymentViewModel model)
        {

            if (ModelState.IsValid)
            {
                var payment = new Payment 
                { 
                 code = model.InsertPaymentViewModel; //or find reference by code...
                 // ... another property etc.
                }
                db.Payments.Add(payment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View();
        }

Upvotes: 2

Related Questions