tags:

views:

46

answers:

3

I have a dropdownlist that I populate with some stuff:

In my controller

ViewData["SourceModelList"] = new SelectList(_modelService.GetAllModels(), "Id", "Description");

in my view

<% using (Html.BeginForm("Compare", "Home")) {  %>
    <p>
        <%=Html.DropDownList("SourceModelList")%>
    </p>
    <p>            
        <input type="submit" value="Compare" />
    </p>
<% } %>

And this renders lovely. Now when I post back to my 'compare' action, how do I find out which item was selected in the drop down?

+1  A: 

The name "SourceModelList" should correspond with the name of a field in your ViewModel, so that the binder has something to bind the value of the dropdown to.

Alternatively, you can pluck the value out of the FormCollection object, if your view is not strongly-typed.

The NerdDinner Tutorial goes into this process in greater detail:

NerdDinner Step 5: Create, Update, Delete Form Scenarios http://nerddinnerbook.s3.amazonaws.com/Part5.htm

Robert Harvey
Thanks Robert. All the replies were correct (+1) but your link helped me to understand a few other things. Ta.
Martin
+1  A: 

You can use any of the regular methods for getting items from a form in ASP.NET MVC: FormCollection, Request object, binding to a specific model or having an action which takes a string SourceModelList parameter.

Yuriy Faktorovich
+1  A: 

You can do:

int value = Convert.ToInt32(Request.Form["SourceModelList"]);

Or by ModelBinders just making sure that your model have a property

public int SourceModelList {get; set;}

And the ModelBinder will get it for you.

Or, but less likely:

public ActionResult Name(FormCollection f, int SourceModelList)
Omar