And click on Ok Button
And select the project template and click on ok
And go to controller Right click on it and select ADD Controller
Demo Controller.cs
public class DemoController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LoadCountries()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "USA", Value = "2" });
li.Add(new SelectListItem { Text = "UK", Value = "3" });
ViewData["Countries"] = li;
return View();
}
public JsonResult GetCityDetails(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
switch (id)
{
case "1":
cities.Add(new SelectListItem { Text = "Select", Value = "0" });
cities.Add(new SelectListItem { Text = "Hyderabad", Value = "1" });
cities.Add(new SelectListItem { Text = "Bangalore", Value = "2" });
cities.Add(new SelectListItem { Text = "Mumbai", Value = "3" });
cities.Add(new SelectListItem { Text = "Tirupathi", Value = "4" });
break;
case "2":
break;
case "3":
break;
}
return Json(new SelectList(cities, "Value", "Text"));
}
}
Right Click on LoadCoutries Method, and Select View
LoadCountries.cshtml
@{
ViewBag.Title = "Address Details";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCityDetails")',
dataType: 'json',
data: { id: $("#Country").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' + city.Text + '</option>');
});
},
error: function (ex) {
alert('Error Message.' + ex);
}
});
return false;
})
});
</script>
@using (Html.BeginForm())
{
<div style="color: Purple;">
@Html.Label("Select County")
</div>
<div>
@if (ViewData.ContainsKey("Countries"))
{
@Html.DropDownList("Country", ViewData["Countries"] as List<SelectListItem>, new { style = "width:250px", @class = "dropdown1" })
}
</div>
<div>
@Html.Label("Select City")
</div>
<div class="editor-field">
@Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), "Select City", new { style = "width:250px", @class = "dropdown1" })
</div>
}
Output:
No comments:
Post a Comment
Thank you for visiting my blog