我正在尝试通过下拉列表中的ajax回传数据,但是ajax调用未回传给控制器
我已经试图在控制器上设置一个断点来检查,但是ajax调用没有回发。
HTML代码
<div class="col-md-6 col-sm-6">
@Html.DropDownList("CategoryId",null,new { @class = "form-control col-md-7 col-xs-12 ", required = "required", id = "CategoryDropDown",
onchange="GetSubCategory()" })
</div>
<div class="col-md-6 col-sm-6">
<select id="SubCategory" class="form-control col-md-7 col-xs-12" required="required"></select>
</div>
Ajax代码
function GetSubCategory() {
var stateId = $("#CategoryDropDown").val();
$.ajax
({
url: '/Home/GetSubCategory',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({
stateId:+stateId
}),
success: function (result) {
$("#SubCategory").html("");
$.each($.parseJSON(result), function (i, SubCategory) {
$("#SubCategory").append($('<option></option>').val(SubCategory.Value).html(SubCategory.Text))
})
},
error: function () {
alert("Whooaaa! Something went wrong..")
},
});
}
控制器代码
[HttpPost]
public ActionResult GetSubCategory(int stateId)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(Logics.SubCategory(MainCatId));
return Json(result, JsonRequestBehavior.AllowGet);
}
我希望ajax调用可以正常工作,并且我可以从此方法中获取子下拉列表
答案 0 :(得分:0)
您的append
语法应类似于以下代码:
$("#SubCategory").append($('<option value="'+ SubCategory.Value +'">' + SubCategory.Text + '</option>')
答案 1 :(得分:0)
你能试试吗
已编辑
function GetSubCategory() {
var stateId = $("#CategoryDropDown").val();
var subCategory = $("#SubCategory");
$.ajax
({
url: '/AdminDevVersion/Home/GetSubCategory',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ stateId:+stateId }),
success: function (result) {
subCategory.empty(); // remove any existing options
$.each($.parseJSON(result), function (i, item) {
subCategory.append($('<option></option>').text(item.Text).val(item.Value))
})
},
error: function () {
alert("Whooaaa! Something went wrong..")
},
});
}
答案 2 :(得分:0)
POST http://localhost/Home/GetSubCategory 404 (Not Found)
所以您可以看到我的项目没有名称,所以我只将mu ajax URL改成
var url = "/AdminDevVersion/Home/GetSubCategory";