我正在做一个mvc 5项目,我有购物车视图,我有2个名为country and state的deopdownlist,当它运行时,国家模型填写国家/地区下拉列表,现在我想填写国家下拉列表更改国家下拉列表所以我使用下面的代码执行此操作,但它不能成功。我调试此代码它正常工作唯一的问题是,此代码无法附加到状态dropdownlist.I不知道该怎么做
@model IEnumerable<NewMVCWebApp.Models.Country>
<script>
function f11() {
var a = $("#se option:selected").text();
var b = $("#se option:selected").index();
$.ajax({
url: "/State/GetStates",
data: { a: a, b: b },
type:"post",
success: function (value) {
cities = JSON.parse(value);
$("#ss").html("");
$("#ss").append("<option>--- please select---</option>");
$.each(cities, function (idx, city) {
$("#ss").append("<option value='" + city.ID + "'>" + city.name + "</option>")
})
},
error: function () {
$("#lbl").html("Error in Ajax...!");
}
})
}
</script>
<div class="tabs-b">
<ul>
<li>estimate</li>
</ul>
<div>
<div>
<p>enter destination</p>
<p class="required">
<label for="sha">Country</label>
<select id="se" name="Country" onchange="f11()">
<option>--- please select ---</option>
@foreach (var item in Model)
{
<option value="@item.ID">@item.name</option>
}
</select>
</p>
<p class="required">
<label>region</label>
<select id="ss"></select>
</p>
<p>
<label for="shc">post code</label>
<input type="text" name="shc" id="shc" required="">
</p>
<p class="link-c">@*<a href="./">get</a>*@</p>
</div>
<div>
<p></p>
</div>
<div>
<p></p>
</div>
</div>
</div>
控制器中的操作
public string GetStates(string a,string b)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<state> states = _context.states.Where(x => x.IDK == Idk).ToList();
return js.Serialize(states.Select(x => new { ID = x.ID, name = x.name }));
}
答案 0 :(得分:0)
在控制器更改方法类型为JsonResult
public JsonResult GetStates(int index)
{
JsonResult json = new JsonResult();
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
json.Data = _context.states.Where(x => x.IDK == index).ToList();
return json;
}
和html文件
function f11() {
var index = $("#se option:selected").val();
$.ajax({
url: "/State/GetStates",
data: { index: index },
type:"post",
success: function (value) {
var result = "";
$("#ss").append("<option>--- please select---</option>");
$.each(value, function (index, city) {
result += "<option value='" + city.ID + "'>" + city.name + "</option>";
});
$("#ss").append(result);
},
error: function () {
$("#lbl").html("Error in Ajax...!");
}
})
}