Below is my code, I am not sure what i am doing wrong?
Ajax json jquery code
function FillCity() {
var countryid = $("select[name$='.countryid']").val(); //<---- this is dynamic
$.ajax({
url: "Controller/FillMyCity",
type: "POST",
dataType: "json",
data: { country: countryid } ,
success: function (city) {
$("select[name$='.cityid']").html(""); // <--- this is dynamic
$.each(city, function (i, pp) {
$("select[name$='.cityid']").append(
$('<option></option>').val(pp.cityid).html(pp.name));
});
},
error: function (err) {
alert(err);
}
});
}
Controller method
public JsonResult FillMyCity(int country)
{
var cities = db.Cities.Where(x => x.countryid == country).ToList().Select(item => new City
{
cityid = item.cityid,
name = item.name
}).AsQueryable();
return Json(cities, JsonRequestBehavior.AllowGet);
}
View
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries", #id = "mycountry" + i + "", #onchange = "FillCity()" })
#Html.DropDownList("City[" + i + "].cityid", new SelectList(Enumerable.Empty<SelectListItem>(), "cityid", "name"), "Select city", new { #class = "form-control cities", #id = "mycity" + i + "" })
Output
EmployeeName Country City
Jenny ddl of countries ddl of cities
John ddl of countries ddl of cities
Problem 1: When I select country for Jenny, the cities ddl for both Jenny + John both get populated with Jenny's Country's cities, but it should only just applied for Jenny. When I select country for John the cities ddl list doesn't get populate So only Jenny's works, John doesn't
Problem 2: Since it is a dynamic json jquery appended html, I am unable to save the cities value, this is due to the fact that it is dynamic and doesn't appear in the view source.
Your use of $("select[name$='.countryid']").val(); will only ever select the value of the first element that has a name attribute ending with .countryid.
In addition, you use of DropDownList("Country[" + i + "].countryid", ...) is not the correct way to generate controls for a collection and its unlikely that will ever bind correctly to your model, however you have not shown the model so that cannot be fixed, so based on your current code, your view should be
<div class="container">
#Html.DropDownList("Country[" + i + "].countryid", (SelectList)ViewData[countries], string.Empty, new { #class = "form-control countries" })
#Html.DropDownList("City[" + i + "].cityid", Enumerable.Empty<SelectListItem>(), new { #class = "form-control cities" })
</div>
and the script
$('.countries').change(function() {
var country = $(this).val();
var cities = $(this).next('.cities'); // get the associated cities dropdownlist
cities.empty(); // clear existing options
$.ajax({
url: '#Url.Action("FillMyCity")', // do not hard code url's
type: "POST",
dataType: "json",
data: { country: country } ,
success: function (data) {
if (data) {
cities.append($('<option></option>').val('').text('Select city'));
$.each(data, function (index, item) {
cities.append($('<option</option>').val(item.cityid).html(item.name));
});
} else {
// oops
}
},
error: function (err) {
alert(err);
}
});
});
and finally, return a collection of anonymous objects containing only the data you need in the view to avoid sending extra data that will not be used
public JsonResult FillMyCity(int country)
{
// No need for .ToList()
var cities = db.Cities.Where(x => x.countryid == country).Select(item => new
{
cityid = item.cityid,
name = item.name
});
return Json(cities); // its a POST so no need for JsonRequestBehavior.AllowGet
}
Related
At present I have two tables (Teams and Employees)
I am populating the dropdownList for Teams perfectly, next I am trying to populate the second dropdownlist depending on the selectedId of Teams for Employees.
Controller:
// GET: CalView
public ActionResult Index(string ses, string DH)
{ //Team Lead Members
var eID = Convert.ToInt32(Session["currentEmployeeID"]);
var EmpID = Session["currentEmpID"];
Employee obj = (from o in db.Employees
where o.EnrollNumber == EmpID
select o).FirstOrDefault();
Department dept = (from dep in db.Departments
where dep.LeadBy == obj.EmployeeId
select dep).FirstOrDefault();
//this works fine
ViewBag.showTeams = new SelectList(db.Teams.Where(tm => (tm.DeptID == dept.DepartmentId) && (dept.LeadBy == eID)), "TeamID","Name");
//this obviously does not
ViewBag.showMembers = new SelectList(db.Employees.Where(empt => (empT.TeamID == selectedIdFromPreviousDropDownList), "EmployeeID", "Employee"));
return View();
}
View:
if ((Session["UT"] == "DD") && (#ViewBag.DeptLead != null))
{
//this works
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
//this does not work
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { #class = "form-control" })
}
Do I need some AJAX call? or perhaps a POST method? Totally new to MVC.
Do I need some AJAX call? or perhaps a POST method? Okay then, lets do it this way:
Give your DropdownLists some id's probably:
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new {id = "ddshowMembers", #class = "form-control" })
Create a jsonResult function, GetMembers and some Magic right there:
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
console.log("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembers")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("wich ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
and in your controller:
public JsonResult GetMembers(int id)
{
return Json(new SelectList(db.Employees.Where(empt => (empt.TeamId == id)), "EmployeeID", "FirstName"));
}
Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName , ContactPerson are Cascading Dropdown and Email and MobileNo are textboxes.
If I select the CustomerName related ContactPerson will load automatically load in ContactPerson dropdown.
If i select the Contactperson the ContactPerson related Email and PhoneNo will load automatically in Email and PhoneNo textbox. I did this all task completely and all are working fine. Now what i need is i wish to reduce the code .
My Controller Code
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEmailByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var contact1 = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault().Email1;
if (contact1 == null)
{
var contact2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Email2;
contact1 = contact2;
}
return Json(contact1, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var mobile1 = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault().Mobile1;
if (mobile1 == null)
{
var mobile2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Mobile2;
mobile1 = mobile2;
}
return Json( mobile1, JsonRequestBehavior.AllowGet);
}
My View Code
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
My Json Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetEmailByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data);
}
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#MobileNo").val(data);
}
});
});
See my coding i wrote separate json and jquery , ajax code for Email and PhoneNo. I feel it is not good . I wish to short my code. I want to pass multiple parameter using json. I want to pass the Email and phone while selecting the ContatcPerson in ContactPerson dropdown. it also effect performance of my application. please any one give solution and suggestion for my problem.
Advance Thanks..
Why don't you return an object from your controller that contains all the information that you need?
Any object serialized to Json can be returned as a JsonResult.
You could even do anonymous types like:
var details = new { email = "test#test.com", phone = "1234567"};
return Json(details);
Everything seems OK but value shows empty..
I have 2 dropdownlist, when I choose first one, I got the index and used ajax to fill other dropdownlist.. But problem is that I dont have result.. loop that is in ajax, doesnt work.. and I checked web tool of firefox, result seems empty, but in C# code, the list has items..
so here is my ajax
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
$.each(data, function (index,item) {
//here is not working !!!
alert("hobaaa: " + index);
alert("data: " + item.Text);
// alert(option.ID + " " + option.politicName);
// electionCombo.append($('<option></option>').val(option.Value).html(option.Text));
});
}
here is my c# code
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ElectionList(int electionTypeId)
{
var service = new EvoteServicesProviderClient();
try
{
var electtionType = service.getAllElectionTypes().FirstOrDefault(e => e.ID == electionTypeId);
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
var list = new SelectList(res, "Value", "Text");
return Json(list, JsonRequestBehavior.AllowGet);
// return Json(new { success = true, result = list },
// JsonRequestBehavior.AllowGet);
}
catch{}
return Json(new { success = false, message = "An error occured" }, JsonRequestBehavior.AllowGet);
}
this is the html side
#using (Html.BeginForm("ElectionList", "Home", FormMethod.Post, new {#class = "form-horizontal", id = "electionlistform"}))
{
#Html.LabelFor(m => m.SelectedElectionId, new {#class = "col-md-2 control-label"})
#Html.DropDownListFor(m => m.SelectedElectionId, Model.ElectionList, new {#class = "form-control", id = "electionList"})
#Html.ValidationMessageFor(m => m.SelectedElectionId)
}
As I wrote, the list is not empty (in actionresult ElectionList)
What I am missing?
Try this :
$.each(data, function () {
//here is not working !!!
alert("hobaaa: " + this.Value);
alert("data: " + this.Text);
});
You can access the property directly because it's json.
UPDATE
Just return the list server side :
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
return Json(res, JsonRequestBehavior.AllowGet);
What I do when I need to fill a dropdown is the same as you, but I'm using a for loop instead of each (maybe it's the same but for me it's working). And by the way, in your ajax code sample you are not closing the ajax function. Hope in your real code it's okay.
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
for (i in data) {
var result = data[i];
// electionCombo.append($('<option></option>').val(result.Value).html(result.Text));
}
}
});
By the way, if it's still not working , you could try a ViewModel with the options you need
public class ViewModelExample
{
public Int32 ValueOption { get; set; }
public String TextOption { get; set; }
}
And use it in your list instead of selectlist. With viewmodels I don't have problems getting the values with json.
I have MVC4 web-application with 2 cascading dropdownlists (parent and child) and button with post action for filtering data dislpayed in grid depending on selected values in dropdownlists. Cascading dropdownlists I realized with Microsoft AJAX (Ajax.BeginForm helper), almost as described here: http://weblogs.asp.net/raduenuca/archive/2011/03/20/asp-net-mvc-cascading-dropdown-lists-tutorial-part-3-cascading-using-microsoft-ajax-ajax-beginform-helper.aspx. BTW, dropdownlists are located in partial view.
The problem is that when I click button, postback is performed and selected values in cascading dropdownlists are reset to original values, i.e. "Please, select value".
Does anybody know how to solve this problem?
Thanks in advance for all who give an answers!
Here is my code with partial view with cascading dropdownlists:
<script type="text/javascript">
$(function () {
$('#Sections').change(function () {
var sectionId = $("#Sections :selected").val();
if (sectionId != "") {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetDocumentTypesList", "DocumentTypes")',
data: { "id": sectionId },
dataType: "json",
success: function (data) {
var items = "";
$.each(data, function (i, documentType) {
items += "<option value='" + documentType.Value + "'>" + documentType.Text + "</option>";
});
$('#Types').html(items);
},
error: function (result) {
alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
}
});
}
else {
var items = '<option value="">Select</option>';
$('#Types').html(items);
}
});
});
#Html.DropDownList("Sections", new SelectList(ViewBag.Sections, "Id", "Name"), "Please select parent type", new { id = "Sections" })
#Html.DropDownList("Types", new SelectList(ViewBag.Types, "Id", "Name"), "Please select child type", new { id = "Types" })
And here is controller code for partial view:
public class DocumentTypesController : Controller
{
static List<DocumentType> documentTypes = DocumentsDAL.GetDocumentTypes(true, true, false);
// GET: /DocumentTypes/
public ActionResult Index()
{
var root = documentTypes.Where(d => d.ParentId == null).ToList();
ViewBag.Sections = root;
ViewBag.Types = new List<DocumentType> { new DocumentType { Id = -1, Name = "Select" } };
return PartialView("~/Views/Shared/_DocumentTypes.cshtml", root);
}
// Get values for parent dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypesList(string id)
{
var items = GetDocumentTypes(Convert.ToInt32(id)).Select(a => new SelectListItem
{
Text = a.Name,
Value = a.Id.ToString(CultureInfo.InvariantCulture)
});
return Json(items, JsonRequestBehavior.AllowGet);
}
// Get values for child dropdownlist.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetDocumentTypeData(string sectionId, string typeId)
{
var documentTypeData = GetDocumentTypes(Convert.ToInt32(sectionId))
.First(d => d.Id == Convert.ToInt32(typeId));
return Json(documentTypeData, JsonRequestBehavior.AllowGet);
}
private static IEnumerable<DocumentType> GetDocumentTypes(int id)
{
return documentTypes.First(d => d.Id == id).DocumentTypes;
}
}
And this is a base view where it's used partial one:
#using (Ajax.BeginForm("Index", null, new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "documentsGrid"
}, new { #class = "form-inline" }))
{
<div>
#{ Html.RenderAction("Index", "DocumentTypes", new { area = "" }); }
</div>
<p class="form-inline">
#Html.LabelForModel(#Resources.LabelPeriodFrom)
#Html.Raw(" ")
#Html.TextBox("periodFrom", "", new { #class = "input-small" })
#Html.Raw(" ")
#Html.LabelForModel(#Resources.LabelPeriodTo)
#Html.Raw(" ")
#Html.TextBox("periodTo", "", new { #class = "input-small" })
#Html.Raw(" ")
<input type="submit" class="btn" value="Filter" />
</p>
}
And controller for basic view with post-action Index, which fired when user press button:
public class IssuerDocumentsController : Controller
{
static readonly IEnumerable<IssuerDocument> Documents = DocumentsDAL.GetDocuments(1, 1).AsEnumerable();
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var documents = Documents.AsEnumerable();
// Check if document section filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Sections")))
{
var documentSectionId = Convert.ToInt32(collection.Get("Sections"));
documents = documents.Where(d => d.SectionId == documentSectionId);
}
// Check if document type filter is applied.
if (!string.IsNullOrEmpty(collection.Get("Types")))
{
var documentTypeId = Convert.ToInt32(collection.Get("Types"));
documents = documents.Where(d => d.TypeId == documentTypeId);
}
return View(documents);
}
}
I have two dropdownlist. The selected value from the first one loads the other. How do I do that when I have the helper methods in a controller?
#using (Html.BeginForm())
{
<div>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><b>Select a District:</b></td>
<td>#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
<tr>
<td><b>Select a TM:</b></td>
<td>#Html.DropDownListFor(m => m.TMId, ViewData["TMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
private void LoadDistrictManagers()
{
var _DMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "District Manager"
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["DMManagers"] = new SelectList(_DMS, "ChannelGroupId", "Name");
}
private void LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["TMManagers"] = new SelectList(_TMS, "ChannelGroupId", "Name");
}
public ActionResult SummaryReport()
{
DistrictManagerModel model = new DistrictManagerModel();
LoadDistrictManagers();
return View("AreaManager", model);
}
Give both dropdowns unique IDs using the HTTPAttributes field:
#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One", new {#id="ddlDMManagers"})
2nd dropdown should be initialized as an empty list:
#Html.DropDownListFor(m => m.TMId, Enumerable.Empty<SelectListItem>(), new {#id="ddlTMManagers"})
If you don't mind using jQuery ajax to update the 2nd dropdown when a 'change' event is triggered on the 1st dropdown:
$(function() {
$('select#ddlDMManagers').change(function() {
var districtId = $(this).val();
$.ajax({
url: 'LoadTerritoryManagers',
type: 'POST',
data: JSON.stringify({ districtId: districtId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, TMManagers) {
$('select#ddlTMManagers').append('<option value="0">Select One</option>');
// loop through the TM Managers and fill the dropdown
$.each(TMManagers, function(index, manager) {
$('select#ddlTMManagers').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});
});
});
Add this class to your controller namespace:
public class TMManager
{
public int Id {get; set;}
public string Name {get; set;}
}
You will need to update your controller action, LoadTerritoryManagers(), to respond to the ajax request and return a JSON array of {Id,Name} objects.
[HttpPost]
public ActionResult LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new TMManager(){ Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_TMS == null)
return Json(null);
List<TMManager> managers = (List<TMManager>)_TMS.ToList();
return Json(managers);
}
Use the following code. It is used in my project. For Zone and Region I used two drop-down list. On change Zone data I loaded the Region drop-down.
In View page
#Html.DropDownList("ddlZone", new SelectList(#ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { #class = "LoginDropDown" })
#Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { #class = "LoginDropDown" })
The Zone need to load when the view page is load.
In the controller write this method for Region Load
[WebMethod]
public JsonResult LoadRegion(string zoneCode)
{
ArrayList arl = new ArrayList();
RASolarERPData objDal = new RASolarERPData();
List<tbl_Region> region = new List<tbl_Region>();
region = erpDal.RegionByZoneCode(zoneCode);
foreach (tbl_Region rg in region)
{
arl.Add(new { Value = rg.Reg_Code.ToString(), Display = rg.Reg_Name });
}
return new JsonResult { Data = arl };
}
Then use the following JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#ddlZone').change(function () {
LoadRegion(this.value);
});
function LoadRegion(zoneCode) {
$.ajax({
type: "POST",
url: '#Url.Action("LoadRegion", "RSFSecurity")',
data: "{'zoneCode':'" + zoneCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlRegion').get(0).options.length = 0;
$('#ddlRegion').get(0).options[0] = new Option("--Select--", "0");
$.map(data, function (item) {
$('#ddlRegion').get(0).options[$('#ddlRegion').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Failed to load Item");
}
});
}
});
</script>
We can use the jquery to get and fill the dropdown like this:
<script>
function FillCity() {
var stateId = $('#State').val();
$.ajax({
url: '/Employees/FillCity',
type: "GET",
dataType: "JSON",
data: { State: stateId},
success: function (cities) {
$("#City").html(""); // clear before appending new list
$.each(cities, function (i, city) {
$("#City").append(
$('<option></option>').val(city.CityId).html(city.CityName));
});
}
});
}
</script>
For more detail see
MVC DropDownListFor fill on selection change of another dropdown