Nick LaMarca
Nick LaMarca

Reputation: 8188

Getting Selected Item From a Dropdown MVC

I created a dropdown like this:

 <%= Html.DropDownList("Nick") %> 

When a user selects an item I wanna send the text of the item back to a controller Action. I am guessin I add the same name of the the get controller with an [HTTPPOST] attribute, but how do I pass the selected item text into the controller?

I want this 2 happen in 2 scenerios -When a user selects an item -Add a button to the html (im not sure the best way??) and when a user clicks the button

the dropdowns selected text is sent.

I am populating the dropdown from ViewData["items"] i populated in the controller.

Upvotes: 0

Views: 998

Answers (2)

Serge Wautier
Serge Wautier

Reputation: 21878

You need a form. You need to populate the drop down. And if you want the form to be sent as soon as the item is selected, you need half a line of javascript.

<% using (Html.BeginForm()) { %>
  <%: Html.DropDownList("nick",
        new SelectList[] { new[] { "hello", "world", "wazza" } }, 
        new { @onchange = "this.form.submit()" })%>
<% } %>

You may also want your controller to receive a value rather than the text in the list option. See the SelectList class for more details.

Upvotes: 1

Vadim
Vadim

Reputation: 17957

Have your form submit to this action.

public ActionResult MyAction(string nick)
{
   //do stuff
}

Upvotes: 0

Related Questions