Robert Jaskowski
Robert Jaskowski

Reputation: 823

Pass Select into Controller via Response

Hy,

I'm new to ASP.NET MVC 5. I'm trying to get the value of an HTML select with no success.

My View (essential part):

<div class="form-group">
    @Html.Label("Country", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("Countries", (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control", id = "Country", name = "Country" })
    </div>
</div>

My Controller (essential part):

public ActionResult Index()
{
    string country = Request["Country"]; // here I always get null
}

I need a newbie like explanation why this is not working and how I get it to work, please :)

Upvotes: 0

Views: 58

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

First, I agree with @Maess. Don't use ViewBag. It's horrible and someone at Microsoft should be slapped for ever adding it as an option in the first place.

That said, your error is pretty obvious here. You named your select "Countries" and you're trying to pull "Country" out of the request.

Since you're new, I'll be nice and lay out how to use a view model for this. First, create a model:

public class IndexViewModel
{
    public int SelectedCountry { get; set; }
    public IEnumerable<SelectListItem> CountryChoices { get; set; }
}

Then in your action:

// GET
public ActionResult Index()
{
    var model = new IndexViewModel();

    // get your country list somehow

    // where `Id` and `Name` are properties on your country instance.
    model.CountryChoices = countries.Select(m => new SelectListItem { Value = m.Id, Text = m.Name });

    return View(model);
}

And in your view:

@model Namespace.IndexViewModel

...

@Html.DropDownListFor(m => m.SelectedCountry, Model.CountryChoices, new { @class = "form-control" })

And finally, in your POST action:

[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    // use model.SelectedCountry
}

Upvotes: 2

Related Questions