ThanksInAdvance ThanksInAdvance - 5 months ago 22
Javascript Question

Pass drop-down list values from view to controller

I have a select tag with several options and each of the options are designated a value.

<select id="dropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>


Additionally, I have the following JQuery script.

$(function() {
$(#dropdown).change(function() {
var option = $(this).find("option:selected").text();
var optionValue = $(this).val();


I've checked both values using an 'alert' and they're correct. Now I want to pass these values from the view to the controller. I put the select tag within a form and tried using '.submit()' on both values, but that causes the script to crash. I'm not sure if I'm using '.submit()' correctly, as I'm a beginner in JavaScript and Jquery. So in short, how can I get the option tag value into a method of my controller?

EDIT 1

The select tags are in a form, and I've been trying to submit like this:

$(this).val().submit()


EDIT 2

Additionally, here is the controller method I'm trying to get the value into.

[HttpPost]
public ActionResult Index(string dropdown)
{
string value = dropdown;

//--- conditional logic ---

return View()
}

Answer

To use submit() your dropdown must be in a <form>

<form method="POST" action="yourControllerUrl/MyAction">
    <select id="dropdown" name="dropdownName">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
     </select> 
</form>

And in the controller :

public ActionResult MyAction(string dropdownName)
{        
      // use your dropdown value here 
}
Comments