Mihir Kadiya
Mihir Kadiya

Reputation: 1

Get variable value from view to Controller in Asp.net mvc 4

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?

Upvotes: 0

Views: 1234

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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)
{
    ...
}

Upvotes: 2

Related Questions