Asp.net Mvc Cascading Dropdownlists Javascript Issues
After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post:
Solution 1:
I have done this several times with something like this:
Create a partial to popolate dropdown list. Name it DropDownList
and put in Shared
folder of Views
@model SelectList
@Html.DropDownList("wahtever", Model)
Your create view should be something like this (skipped irrelevant parts)
<scripttype="text/javascript">
$(function() {
$("#StateId").change(function() {
loadLevelTwo(this);
});
loadLevelTwo($("#StateId"));
});
functionloadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax({
url: "@Url.Action("GetCities")",
type: "GET",
data: {stateId: selectedId},
success: function (data) {
$("#CityId").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
</script>
@Html.DropDownList("StateId")
<selectid="CityId"name="CityId"></select>
Carefully note the Empty Select
item for CityId
and the call of loadLevelTwo
at document.ready
And your controller should be like:
public ActionResult Create()
{
ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
return View();
}
public ActionResult GetCities(int stateId) {
SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
return PartialView("DropDownList", model);
}
Solution 2:
Thank you for your assistance,
It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
Post a Comment for "Asp.net Mvc Cascading Dropdownlists Javascript Issues"