0

Hello I have created Small application in which i declare one dropdown list. Its name is "Country" so i get the value of dropdown list using javascript and store it in a local variable. so how do I use the variable in controller?

1
  • from @Darin's answer- @Html.DropDownListFor(x => x.SelectedValue, Model.Values) basically renders in html markup - <select name="SelectedValue"><option></option></select>, Now note the name of this element. Ultimately when you submit the form the action method retrieves the value by the name of that element. You don't need to store the value in any local variable. Commented Jan 28, 2015 at 12:21

1 Answer 1

2

If this dropdown is inside an html <form> when this form is submitted to the server, you can retrieve the selected value from the dropdown.

Example:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedValue, Model.Values)
    <button type="submit">OK</button>
}

When the form is submitted you can retrieve the selected value in the corresponding controller action:

[HttpPost]
public ActionResult Index(string selectedValue)
{
    // The selectedValue parameter will contain the value from the
    // dropdown list
    ...
}

Alternatively if you have more elements in your form that you want to be sent you can define a view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    ... some other properties
}

that your controller action can take as parameter:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    ...
}

If your dropdown is not inside an html form you can submit the selected value of the dropdown using AJAX. Example:

$.ajax({
    url: '@Url.Action("SomeAction")',
    type: 'POST',
    data: { selectedValue: 'the selected value you retrieve from the dropdown' },
    success: function(result) {
        alert('successfully sent the selected value to the server');
    }
});

And your controller action might look like this:

[HttpPost]
public ActionResult SomeAction(string selectedValue)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.