Reputation: 63
I have populated two DropDownList in my View:
<tr>
<td class="info_label">City</td>
<td>@Html.DropDownListFor(m=>m.User.City,Model.City,"-- Chọn thành phố --",new { @class = "dropdown" })</td>
</tr>
<tr>
<td class="info_label">Ward</td>
<td>@Html.DropDownListFor(m => m.User.Ward, Model.Ward, "-- Chọn quận --" ,new { @class = "dropdown" })</td>
</tr>
When i change the value of the first ddl, the second ddl also change depend on the value of the first. And i have a jquery script to achieve that. Here is my jquery code:
function LocationValue() {
$("#User_City").change(function () {
var cityName = $("#User_City").val();
if (cityName == null) {
$("Ward").prop("disabled", true);
}
else {
$("Ward").prop("disabled", false);
getWards(cityName);
}
});
}
function getWards(cityName) {
$.ajax({
url: "/Checkout/Wards",
data: { CityName: cityName },
dataType: "json",
type: "POST",
error: function () {
return;
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#User_Ward").html(items);
}
});
}
and the Post method in my controller:
[HttpPost]
public ActionResult Cities()
{
var cities = ILocaRepo.Cities;
return Json(new SelectList(cities,"CityID","CityName"));
}
[HttpPost]
public ActionResult Wards(string CityName)
{
var wards = ILocaRepo.ListWardByCityName(CityName);
return Json(new SelectList(wards, "WardID", "WardName"));
}
For some reason, the source of 2 ddl have Value = x.CityName.ToString()
, not have CityID(int). In firebud, why the repsone of the second ddl always is []
. Any suguestion for my error?
Upvotes: 0
Views: 187
Reputation: 1038710
In firebud, why the repsone of the second ddl always is []
Probably because the ListWardByCityName
method that you are calling returns an empty list. This could happen if this method doesn't find the corresponding entry by city name. Debug this method to see why this happens.
As a side remark you seem to be using some $('#User_City')
selector but your dropdown doesn't have such id. Make sure you have assigned the proper id to it:
@Html.DropDownListFor(
m => m.User.City,Model.City,
"-- Chọn thành phố --",
new { @class = "dropdown", id = "User_City" }
)
Upvotes: 1