Fiz a seguinte função:
$("#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"));
}
Meu problema é que ela sempre cai na exceção...
Já descobri que o problema está na montagem do 'setRequestHeader' no 'XMLHttpRequest. Ele não está funcionando com HTTPS.
Quando faço o seguinte código funciona:
var http = new XMLHttpRequest();
var url = "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);
Alguém tem ideia de solução para usar o Json?
console.log(ex)
ai você vai saber qual é o erro que está dando, complemente a pergunta com esse resultado, para que a comunidade posso te ajudar melhor.dataType
parahtml
e funcionou.