Hosea146
Hosea146

Reputation: 7702

MVC 4 - How to get the selected item from a dropdown list

I am very new with MVC. I have the following Razor code:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset style="margin:5px">
        <legend>List a Bicycle for Sale</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.BicycleManfacturer)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ManufacturerList")
        </div>

        ....
        ....


        <div class="float-right">
            <input type="submit" value="List Bike" />
        </div>
    </fieldset>
}

"ManufacturerList" is a List of SelectedListItem stored in the ViewBag (I didn't want to create models for all my dropdown lists). It's build via this method:

    private void HydrateManufacturerList()
    {
        var manufacturerList = (from row in db.BicycleManufacturer.ToList()
                                select new SelectListItem
                                {
                                    Text = row.Description,
                                    Value = row.BicycleManufacturerId.ToString()
                                }).ToList();
        manufacturerList.Add(new SelectListItem
        {
            Text = "-- Select Manufacturer --",
            Value = "0",
            Selected = true
        });
        ViewBag.ManufacturerList = manufacturerList.OrderBy(row => row.Text);
    }

I have the following code that gets called when a Submit is done:

    [HttpPost]
    public ActionResult Create(BicycleSellerListing bicyclesellerlisting)
    {
        bicyclesellerlisting.ListingDate = System.DateTimeOffset.Now;

        if (ModelState.IsValid)
        {
            db.BicycleSellerListing.Add(bicyclesellerlisting);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(bicyclesellerlisting);
    }

What I can't figure how to get the selected manufacturer from the dropdown list when the user posts the view back to my controller and this method is executed.

Upvotes: 1

Views: 4565

Answers (1)

Murtoza
Murtoza

Reputation: 171

Use

public ActionResult Create(BicycleSellerListing bicyclesellerlisting, FormCollection collection)
{ 
  ...

You can get all the inputs including the drop down selected items like collection["ManufacturerList"] or similar depending on your drop down list name.

Upvotes: 1

Related Questions