I've done the following function:
$("#CategoryList").change(function () {
$("#SubCategoryDropDown").empty();
$.ajax({
dataType: "json",
url: '@Url.Action("GetSubCategory", "ProjectSubCategories")',
type: 'POST',
data: { id: $("#CategoryList").val() },
success: function (SubCategories) {
$("#SubCategoryDropDown").append('<option value="0">' + '--Selecione uma SubCategoria--' + '</option>');
$.each(SubCategories, function (i, SubCategory) {
$("#SubCategoryDropDown").append('<option value="' + SubCategory.Value + '">' + SubCategory.Text + '</option>');
});
},
error: function (ex) {
alert('Falha ao retornar Subcategoria.' + ex);
}
});
Controller:
public JsonResult GetSubCategory(int id)
{
var SubCategoryDropDown = new List<ProjectSubCategory>();
using (var context = new ApplicationDbContext())
{
SubCategoryDropDown = context.ProjectSubCategories.Where(x => x.CategoryId.Equals(id)).ToList();
}
return Json(new SelectList(SubCategoryDropDown, "SubCategoryId", "SubCategoryDescription"));
}
My problem is that it always falls into the exception ...
Cansomeonehelpme?Thanks!
Ihavealreadydiscoveredthattheproblemisintheassemblyof'setRequestHeader'inthe'XMLHttpRequest.ItisnotworkingwithHTTPS.
WhenImakethefollowingcodeitworks:
varhttp=newXMLHttpRequest();varurl="https://localhost:44399/ProjectSubCategories/GetSubCategory";
var params = "id="+$("#CategoryList").val();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText)
ProjectSubCategories = JSON.parse(http.responseText);
$("#SubCategoryDropDown").append('<option value="0">' + '--Selecione uma Subcategoria--' + '</option>');
$.each(ProjectSubCategories, function (i,ProjectSubCategory) {
$("#SubCategoryDropDown").append('<option value="' + ProjectSubCategory.Value + '">' + ProjectSubCategory.Text + '</option>');
// here we are adding option for States
});
}
}
http.send(params);
Does anyone have a solution to use Json?