我有两个下拉列表,如国家和州。我需要根据国家/地区值加载状态。
我创建了一个ajax Call并执行countrydropdown的更改事件。
现在我的问题是如何根据国家/地区下拉值加载州下拉列表
Model
public SelectList statename { get; set; }
public string selectedvalue { get; set; }
Controller
[HttpPost]
public ActionResult form(displayModel disp)
{
var display = new displayModel();
List<string> state = new List<string>();
if (disp.selectedvalue == "India")
{
state.Add("TN");
state.Add("KL");
state.Add("UP");
}
display.statename = new SelectList(state, "--select--");
return View(display);
}
View
@Html.LabelFor(model=>model.statename)
@Html.DropDownListFor(model => model.statename, Model.statename, new { id="dropstate"})
$("#dropdown1").change(function () {
$.ajax({
url: "/Home/form",
type: "post",
data: {
selectedvalue: $("#dropdown1 option:selected").text()
},
success: function (data) {
alert(data);
}
});
});
答案 0 :(得分:0)
这个链接应该有助于这样做, http://devingredients.com/2011/05/populate-a-select-dropdown-list-with-jquery/
但是,不是像上面链接中提到的那样硬编码值,而是可以进行ajax调用来获取数据。
答案 1 :(得分:0)
您可以使用这样的ajax调用来调用一个控制器方法,该方法将代表所选的id返回json,然后在下拉列表中填充结果
Controller:
public JsonResult GetStateList() {
var list = new List<ListItem>() {
new ListItem() { Value = "1", Text = "VA" },
new ListItem() { Value = "2", Text = "MD" },
new ListItem() { Value = "3", Text = "DC" }
};
return this.Json(list);
}
$(function() {
$("#dropdown1").change(function () {
$.getJSON("/Home/GetStateList", { Id: $("#dropdown1 option:selected").val() },
function(fooList) {
$("#state").empty();
$.each(fooList, function(i, foo) {
$("#state").append(""+ foo.Value + "");
});
});
});
});
答案 2 :(得分:0)
您可以将selectedCountryId
发送到控制器,然后将State
列表项填充为 JSON 数据。
Ajax代码:
$('#dropdown1').change(function () {
var selectedCountryId = $(this).val();
$.getJSON('@Url.Action("form")', { countryId: selectedCountryId }, function (data) {
var select = $('#dropstate');
select.empty();
$.each(data, function (index, sta) {
select.append(
$('<option/>')
.attr('value', sta.Value)
.text(sta.Text)
);
});
});
});
控制器代码:
public ActionResult form(int countryId)
{
//Here you can check the countryId & if any logic you want
//Or Else you can call the service method here and opcode StateListItems,
//If so then you have make a little change to the below JSON data
var stateList = new List<StateItem>()
{
new ListItem() { Value = "1", Text = "AndraPradesh" },
new ListItem() { Value = "2", Text = "Karnataka" },
new ListItem() { Value = "3", Text = "TamilNadu" }
};
var rows = service.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}