Ajax request does not work - success does not work

3

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?

    
asked by anonymous 19.08.2017 / 23:07

1 answer

0

Your API should return a JSON, not a C # object.

public JsonResult GetSubCategory(int id)
{
    var subCategories = new List<ProjectSubCategory>();
    using (var context = new ApplicationDbContext())
    {
        subCategories = context.ProjectSubCategories
            .Where(x => x.CategoryId.Equals(id))
            .ToList();
    }
    return Json(subCategories);
} 
    
22.08.2017 / 09:23