Для параметров устанавливается значение null при переходе от Ajax к ASP. NET Основной контроллер - PullRequest
1 голос
/ 30 мая 2020

У меня возникла проблема с отправкой данных с использованием Ajax на ASP. NET Основной контроллер.

У меня есть сущность с такой структурой:

public class ProprieteBienFinance
{
    public int ProprieteBienFinanceId { get; set; }
    public string Libelle { get; set; }
    public int Rang { get; set; }
    public virtual ICollection<ChoixPropriete> Modalites { get; set; }
    public TypePropriete TypePropriete { get; set; }

    public ICollection<MetaBlocageAffichagePropriete> BlocageAffichagePropriete { get; set; }
    public string? Dependance { get; set; }

    public ProprieteBienFinance()
    {
        this.Modalites = new List<ChoixPropriete>();
        this.BlocageAffichagePropriete = new List<MetaBlocageAffichagePropriete>();
    }
}

и страница «cs html», на которой отображается список этой сущности. Я установил прослушиватель в этом списке для управления удалением и добавлением участников.

var proprietes = {};
var financement = {
    aInternal: proprietes,
    aListener: function (val) { },
    set a(val) {
        this.aInternal = val;
        this.aListener(val);
    },
    get a() {
        return this.aInternal;
    },
    registerListener: function (listener) {
        this.aListener = listener;
    }
}

financement.registerListener(function (val) {

    var dataToSend = {};
    dataToSend.caracteristiques = proprietes;
    $.ajax
        (
            {
                url: window.location.origin + "/ParametrageBiensFinanciers/AfficherCaracteristiquesFinancement",

                type: "post",

                dataType: "json",

                beforeSend: function (x) {
                    if (x && x.overrideMimeType) {
                        x.overrideMimeType("application/json;charset=UTF-8");
                    };
                    x.setRequestHeader('RequestVerificationToken', document.getElementById('RequestVerificationToken').value);
                },

                data: dataToSend,

                complete: function (result) {
                    // this code is to update the list printed and updated a hidden input
                    $("#displayProperties").html(result.responseText);
                    $(".selectpicker").selectpicker();
                    if (typeof (proprietes) != "undefined")
                        $("#nombreProprietesData").val(proprietes.length);
                    $("#displayProperties").show();

                }
            }
        );
});

Предполагается, что щелчок по ссылке обновления вызывает метод на контроллере и переносит форму для обновления

<a title="Mettre à jour le type de financement" class="btn btn-primary btn-link btn-sm Edit" onclick="LoadUpdateForm(@counter)">
    <i class="material-icons">edit</i>
</a>

function LoadUpdateForm(rowNumber) {
    //les proprietes de base sont le libelle et le type 
    var idLibelleChamps = "#libelle_prop_" + rowNumber;
    var libelle = $(idLibelleChamps).html();

    var caracteristique = {};
    caracteristique = proprietes.find(element => element.rang == rowNumber);

    var dataToSend = {};
    dataToSend.caracteristiqueToUpdate = caracteristique;
    dataToSend.caracteristiques = proprietes;


    debugger;
    $.ajax
        (
            {
                url: window.location.origin + "/ParametrageBiensFinanciers/AfficherFormulaireModifCaracteristique",

                type: "post",

                dataType: "json",

                beforeSend: function (x) {
                    if (x && x.overrideMimeType) {
                        x.overrideMimeType("application/json;charset=UTF-8");
                    };
                    x.setRequestHeader('RequestVerificationToken', document.getElementById('RequestVerificationToken').value);
                },

                data: dataToSend,

                complete: function (result) {

                    $("#AjouterCaracteristiques").html(result.responseText);
                    $(".selectpicker").selectpicker();
                    $("TypePropriete").change(function () {
                        targetType($(this));
                    });
                    var extendedProperty = $("#selectExtendId option:selected");
                    if ((typeof ($(extendedProperty)) != "undefined") && $(extendedProperty).text() != "Choisir la caractéristique dépendante") {
                        var dataToSend = {};

                        dataToSend.libelle = $(extendedProperty).text();
                        dataToSend.caracteristiques = proprietes;
                        dataToSend.caracteristiqueToUpdate = caracteristique;
                        $.ajax
                            (
                                {
                                    url: window.location.origin + "/ParametrageBiensFinanciers/EtendreUneCaracteristique",

                                    type: "post",

                                    dataType: "json",

                                    beforeSend: function (x) {
                                        if (x && x.overrideMimeType) {
                                            x.overrideMimeType("application/json;charset=UTF-8");
                                        };
                                        x.setRequestHeader('RequestVerificationToken', document.getElementById('RequestVerificationToken').value);
                                    },

                                    data: dataToSend,

                                    complete: function (result) {

                                        $("#checkExtendDiv").html(result.responseText);
                                        $(".selectpicker").selectpicker();
                                    }
                                }
                            );
                    }
                    $("#addPropertiesPane").show();
                }
            }
        );
}

Теперь проблема в том, что jQuery хорошо справляется со своей задачей и правильно устанавливает параметры. Но при выполнении запроса, когда свойство Modalites в сущности насчитывает 0 элементов, данные хорошо достигают контроллера. тогда как при подсчете хотя бы 1 элемента данные достигают контроллера с нулевыми значениями. Вот несколько экранов печати проблемы.

enter image description here

Здесь доказательство того, что параметры установлены правильно перед вызовом Ajax. Тогда как-то все равно нулю после.

enter image description here

...