mvcの別のドロップダウンリストからドロップダウンリストでデータをバインドしようとしています。 カテゴリから選択すると、サブカテゴリはコントローラのjsonresultアクションの値を返しますが、ajaxはエラーGeneral Failureを返します。エラーの原因はわかりません。私のjQuery ajax関数は常にエラーを返し、このエラーメッセージは(General Failure)です。
これはこれはビューのコードである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