简体   繁体   中英

Json data from ajax call can't be filtered in onClick trigger

When my page loads, I have an ajax call that runs. When a user selects a checkbox, the code runs through the json data returned by the ajax call to determine which other options to show/hide.

The ajax call is returning the correct data, the onClick triggers are working fine, but when I try to filter the json data (using filter(), or by writing my own method using forEach) it fails.

With filter I get an empty array, no matter how I write the command or what qualifiers I use. With forEach, the if() statement I use to check the data returns undefined, no matter how I write it (item.RecipeCategoryOptionID == "idIKnowExists" returns "undefined").

If I insert debugger; and run in Chrome, I can put a breakpoint in the middle of the forEach call and check my if() statement in the console, and I get a real value (in the console, calling item.RecipeCategoryOptionID returns an actual value, not undefined).

I've even tried putting the ajax call in the onClick function, just to force SOMETHING to work (and then putting the filter statement in the success function). It doesn't work that way either.

How do I fix this??

var constraints;

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "@Url.Action("GetConstraints", "RecipeManagement")",
        dataType: "json",
        success: function (data) {
            constraints = data;
        }
    });
});

function CalledOnClick(checkbox) {
    var selectedOptionId = $(checkbox).attr("class");
    var isSelected = $(checkbox)[0].checked;

    ApplyConstraints(selectedOptionId, isSelected);
}

function ApplyConstraints(selectedOptionId, isSelected) {
    var relevantConstraints = constraints.filter(c => { return (c.RecipeCategoryOptionID == selectedOptionId) });

    relevantConstraints.forEach(function (item) {
        $("#isRequired" + item.RecipeCategoryTitleID).val(isSelected ? item.IsRequired : !item.IsRequired);
        $("#isProhibited" + item.RecipeCategoryTitleID).val(isSelected ? item.IsProhibited : !item.IsProhibited);
    });
}

Solved: something in the C# call "return Json(constraints);" was converting the first letter of each property name (key) to lower-case.

So item.RecipeCategoryTitleID became item.recipeCategoryTitleID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM