In this post, we are going to discuss how to get the drop down selected value using Asp.Net MVC razor and jquery.
Contents
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>
thank to post..
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
Thanks for the post..it worked
its worked vary nice
Thanks its very good of passing data from controller to view
i want text to be display after selecting drop down value