I have two tables States and Cities
with two dropdown list that when the state drop down selected the options should be available on Cities dropdown list but somehow Text and Value doesn't appear
State ViewBag and DropDown List
ViewBag.State = new SelectList(db.StateRepository.GetAll(), "StateId", "StateTitle");
@Html.DropDownList("States",(SelectList)ViewBag.State, "Please Select", htmlAttributes: new { @class = "form-control", id="State"})
City Drop down
<select class="form-control" id="City"> </select>
Json in Controller
public ActionResult GetCities(int id)
{
var data = db.Cities.Where(d => d.StateId == id).Select(d => new { Text = d.CityTitle, Value = d.CityId });
return Json(data, JsonRequestBehavior.AllowGet);
}
Script
$("#State").change(function() {
var loading = $('<option></option>').text("Please Wait");
$('#City').attr("disabled", "disabled").empty().append(loading);
$.getJSON("/GetCities/" + $("#State > option:selected").attr("value"),
function(result) {
$("#City").removeAttr("disabled").empty().append($("<option></option)").val("").text("Please Select"));
$.each(result,
function(item) {
$("#City").append($("<option></option>").val(item.value).text(item.text));
});
});
});
By not showing the value and Text I mean like I have 4 Cities for 'x' State on my table, in the view when I change the StateDropDown to 'x' State it just shows 4 empty <option></option>
in my City DropDown list without any text and value
Guys I really appreciate all your help I'm newbie and I have no idea what the problem is so please help.
EDIT: I think the results returned from the controller is returning an object like:
[{ "Text": "..", "Value": ".." }]
So you would want to bind:
$.each(result, function(item) {
$("#City").append($("<option></option>").val(item.Value).text(item.Text));
});
The Value and Text should be upper-cased.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.