Home/MVC/Getting Selected text/value using jquery in MVC Razor

Getting Selected text/value using jquery in MVC Razor

In this post, we are going to discuss how to get the drop down selected value using Asp.Net MVC razor and jquery.

Model :

A simple Model which has Country ID, Country Name and SelectedCounty.

public class UserDetailModel
{
[Display(Name = “CountryDetail”)] public List<Country> CountryDetail;
[Display(Name = “selectedcountry”)]
public string SelectedCountry { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}

Controller :

Here we creating a collection which contain the list of countries for binding in the drop down list.

public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  “INDIA” },
new Country() { CountryId = 2, CountryName= “US” },
new Country() { CountryId = 3, CountryName= “Russia” },
new Country() { CountryId = 4, CountryName= “UK” }
};
return View(obj);
}

[HttpPost]
public void Save(FormCollection form, string selectedCountry)
{
}

View

A simple view which consist of Asp .Net MVC razor drop down list.  This drop down bind the mode which has return from the above view.

@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail, “CountryId”, “CountryName”)

Method 1: (Getting value using JQuery Selector)

<script type=”text/javascript”>
$(document).ready(function() {
$(“select[id^=’SelectedCountry’]”).change(function() {
alert($(‘option:selected’, $(this)).text());
});
});
</script>

Method 2: (Getting value using JQuery Onchange)

@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail,
“CountryId”, “CountryName”),new{onchange = “ddListChange()”  })

<script type=”text/javascript”>
function ddListChange()
{
alert($(‘#SelectedCountry option:selected’).text());
}
</script>

Output

DDL selection using jquery

4 Comments

  1. selvaraj October 22, 2013 at 11:17 am

    thank to post..

  2. gabrielabalasel March 19, 2014 at 3:54 pm

    Hello 🙂 Your article is very helpful!
    Is there any way of getting the selected id in JQuery (here id for “INDIA”) and pass it as a var in razor?

    I have made the same functionnality for my app, and I have to pass the id of the selected item to the controller.

    To pass it I need to asign it to a variable declared in razor.
    Can you help?

    Thank you!!!
    Gabriela

  3. Kavitha February 17, 2016 at 7:33 am

    Thanks for the post..it worked

  4. samir kr parimal July 7, 2017 at 7:05 am

    its worked vary nice

Leave A Comment