我試圖使用mvc中的另一個下拉列表綁定下拉列表中的數據。 當我從類別中選擇子類別在控制器中返回jsonresult操作的值,但ajax給我的錯誤一般失敗,我不知道錯誤在哪裏。我的jQuery ajax函數總是返回錯誤,並且此錯誤消息是(常規失敗)
這是守則Controlle
public ActionResult Create()
{
List<sub_categories> subCategoryList = new List<sub_categories>();
// Select List Category
var dropdownListCategoryEnr = new SelectList(db.category.ToList(), "cat_id", "cat_name_en");
ViewBag.cat_id = dropdownListCategoryEnr;
//Select List Sub category
ViewBag.sub_cat_id = new SelectList(subCategoryList, "sub_cat_id", "sub_name_en");
return View();
}
[HttpGet]
public JsonResult GetSubCategoryById(string categoryId = "")
{
List<sub_categories> subCategoryList = new List<sub_categories>();
int ID = 0;
if(int.TryParse(categoryId, out ID))
{
subCategoryList = db.sub_categories.Where(x => x.cat_id.Equals(ID) && x.is_deleted == false).ToList();
}
if(Request.IsAjaxRequest())
{
return new JsonResult
{
Data = subCategoryList,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not Valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
這是視圖代碼: -
@Html.DropDownListFor(model => model.cat_id, (SelectList)ViewBag.CategoryAr, WhiteWhaleLanguage.PleaseSelect, new { @style = "padding:0 12px;", @class = "form-control" })
@Html.ValidationMessageFor(model => model.cat_id, "", new { @class = "text-danger" })
@Html.DropDownListFor(model => model.sub_cat_id, (SelectList)ViewBag.sub_cat_id, WhiteWhaleLanguage.PleaseSelect, new { @style = "padding:0 12px;", @class = "form-control" })
@Html.ValidationMessageFor(model => model.sub_cat_id, "", new { @class = "text-danger" })
這是jQuery代碼: -
$(document).ready(function() {
$("#cat_id").change(function() {
// this will call when Country Dropdown select change
var categoryId = parseInt($("#cat_id").val());
if (!isNaN(categoryId)) {
var ddsub = $("#sub_cat_id");
ddsub.empty(); // this line is for clear all items from State dropdown
ddsub.append($("<option></option").val("").html("Select State"));
// Here I will call Controller Action via Jquery to load State for selected Country
$.ajax({
url: "@Url.Action("GetSubCategoryById", "Products")",
type: "GET",
data: { categoryId: categoryId },
dataType: "json",
success: function (data) {
$.each(data, function (i, val) {
ddsub.append(
$("<option></option>").val(val.sub_cat_id).html(val.sub_name_en)
);
});
},
error: function (xhr, ajaxOptions, errorThrown) {
alert(xhr.responseText);
}
});
}
});
});
當您發出AJAX請求時,您應該可以在Chrome開發人員工具(F12)中檢查它,並且可能會顯示錯誤消息。 – Luke