Функция Ajax запускается несколько раз и возвращает ошибку - PullRequest
0 голосов
/ 13 мая 2019

Я пытаюсь загрузить информацию из базы данных в таблицу asp.net, используя ajax-вызов WCF, который получает данные из таблицы сущностей и загружает их на веб-страницу.Я использую вызов ajax только один раз, но WCF загружается несколько раз, и он всегда возвращает правильное значение, но полная функция в Ajax переходит к функции ошибки. Вызов ajax отлично работает с другими функциями WCF

WCF:

   #region Employees

    #region Get_Persons
    [OperationContract]
    [
    WebInvoke
    (
    Method = "POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest,
    ResponseFormat = WebMessageFormat.Json,
    RequestFormat = WebMessageFormat.Json
    )
    ]
    public Result_Get_Employees Get_Employees()
    {
        System.Diagnostics.Debug.WriteLine("wcf called"); //being printed multiple times
        #region Declaration And Initialization Section.
        string i_Ticket = string.Empty;
        Result_Get_Employees oResult_Get_Persons = new Result_Get_Employees();
        #endregion
        #region Body Section.
        FuelAppEntities entities = new FuelAppEntities();
            oResult_Get_Persons.My_Result = entities.tbl_User.ToList();
            #endregion
            #region Return Section
            System.Diagnostics.Debug.WriteLine("Result is: "+oResult_Get_Persons.My_Result.Count);//Returing the right value
            return oResult_Get_Persons;
        #endregion
    }
    #region Result_Get_Categories_List
    public partial class Result_Get_Employees : Action_Result
    {
        #region Properties.
        public List<tbl_User> My_Result { get; set; }
        #endregion
    }
    #endregion
    #endregion
    #endregion

    #region Action_Result
    public partial class Action_Result
    {
        #region Properties.
        public string ExceptionMsg { get; set; }
        #endregion
        #region Constructor
        public Action_Result()
        {
            #region Declaration And Initialization Section.
            #endregion
            #region Body Section.
            this.ExceptionMsg = string.Empty;
            #endregion
        }
        #endregion
    }
        #endregion

Javascript:

/* Members */
/* --------------------------------------------------------------- */
var _StartRow = 0;
var _Current_Page = 1;
var _Pages_Count = 0;
var _ChildWindow = "";
var js_Selected_News = null;
var _Person_Grid_Data = "";
var _Person_List = [];
var Params_Get_Person_By_Criteria_InList = new Object();
Params_Get_Person_By_Criteria_InList.data = ko.mapping.fromJS([]);

var _Params_Get_Person_By_Criteria_InList = ko.mapping.fromJS(Params_Get_Person_By_Criteria_InList);


$(document).ready
(
function () {
    console.log("ready");
    $("title", $(window.parent.document)).html('Persons');
    SetControlsProperties();
    setActiveNavigation(2, '');
}
);
/* --------------------------------------------------------------- */

/* SetControlsProperties */
/* --------------------------------------------------------------- */
function SetControlsProperties() {
    try {
        console.log("set control properties");
        /* ----------------- */
        ko.applyBindings(_Params_Get_Person_By_Criteria_InList, $("#news_page")[0]);
        /* ----------------- */
        Btn_Search_Click();
    }
    catch (e) {
        console.log("SetControlsProperties: " + e.message);
    }
}
/* --------------------------------------------------------------- */

/* Btn_Search_Click. */
/* --------------------------------------------------------------- */
function Btn_Search_Click() {
    try {
        console.log("btn search clicked");
        GetData();
    }
    catch (e) {
        console.log("Btn_Search_Click: " + e.message);
    }
}
/* --------------------------------------------------------------- */

/* GetData */
/* --------------------------------------------------------------- */
function GetData() {
    try {

        console.log("get data");
        _Params = ko.mapping.toJSON(_Params_Get_Person_By_Criteria_InList);
       // _Params = null;
        console.log("params: " + _Params);
        _Service_Method = "Get_Employees";
        var request = $.ajax({
        type: "POST",
        url: WCF.svc/Get_Employees,
        data: _Params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function (msg) {
            console.log(msg.login);
            Get_Employees_Completed(msg);
        },
        error: function (msg) {
            console.log("fail: " + msg.responseText + msg.statusText + msg.status)
        }
    });

        /* ---------------- */
    }
    catch (e) {
        console.log("GetData: " + e.message);
    }
}
/* --------------------------------------------------------------- */
// Get_Person_By_Criteria_Adv
/* --------------------------------------------------------------- */
function Get_Employees_Completed(i_Input) {
    try {
        console.log(i_Input.message);
        Handle_Employees_Grid(i_Input);
    }
    catch (e) {
        console.log("Get_Employees_By_Criteria_Adv_Completed: " + e.message);
    }
}
/* --------------------------------------------------------------- */

//Handle_Person_Grid
/* --------------------------------------------------------------- */
function Handle_Employees_Grid(i_Input) {
    try {
        var i_Person_List = [];
        console.log("Length: " + i_Input.My_Result.length)
        for (var i = 0; i < i_Input.My_Result.length; i++) {
            console.log(i_Input.My_Result[i])
            i_Person_List.push("Persons: "+i_Input.My_Result[i]);
        }
        var oTable = $('#tbl_data').dataTable();
        oTable.fnDestroy();
         $('#tbl_data tbody').html("");
        _Person_List = i_Person_List;
        _Params_Get_Person_By_Criteria_InList.data([]);
        _Params_Get_Person_By_Criteria_InList.data(i_Person_List);
        Module.init();

    }
    catch (e) {
        console.log('Handle_Person_Grid :' + e.message);
    }
}
/* --------------------------------------------------------------- */

1 Ответ

0 голосов
/ 14 мая 2019
public Result_Get_Employees Get_Employees()
{
    System.Diagnostics.Debug.WriteLine("wcf called"); //being printed multiple times
    #region Declaration And Initialization Section.
    string i_Ticket = string.Empty;
    Result_Get_Employees oResult_Get_Persons = new Result_Get_Employees();
    #endregion
    #region Body Section.
    FuelAppEntities entities = new FuelAppEntities();
        return entities.tbl_User.ToList();
        #endregion
        #region Return Section
        System.Diagnostics.Debug.WriteLine("Result is: "+oResult_Get_Persons.My_Result.Count);//Returing the right value
        return oResult_Get_Persons;
    #endregion
}

Возможно, что-то не так в фрагментах кода. Вообще говоря, мы должны вернуть список. Возьмите шаблон WCF по умолчанию в качестве примера.
IService1.cs

[OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        List<CompositeType> GetDataUsingDataContract();
[DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
}

Service1.cs

  public List<CompositeType> GetDataUsingDataContract()
    {
        List<CompositeType> lists = new List<CompositeType>()
        {
            new CompositeType()
            {
                StringValue="Hello",
                BoolValue=true
            },
            new CompositeType()
            {
               StringValue="busy",
               BoolValue=false
            },
           new CompositeType()
           {
               StringValue="World",
               BoolValue=true
           }
        };
        return lists;
    }

Knockoutjs переплет.

  <script>
        var model = {
            composites: ko.observableArray()
        };

        function sendAjaxRequest(httpMethod, callback, url) {
            $.ajax("http://10.157.18.36:12000/service1.svc/getdatausingdatacontract", {
                type: httpMethod, success: callback
            });
        }

        function getAllItems() {
            sendAjaxRequest("GET", function (data) {
                model.composites.removeAll();
                for (var i = 0; i < data.length; i++) {
                    model.composites.push(data[i]);
                }
            });
        }

        $(document).ready(function () {
            getAllItems();
            ko.applyBindings(model);
        });
    </script>

Html.

<div class="panel-heading">List Composites</div>
    <div class="panel-body ">

        <table class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th>
                        StringValue
                    </th>
                    <th>
                        BoolValue
                    </th>
                </tr>
            </thead>
            <tbody data-bind="foreach:model.composites">
                <tr>
                    <td data-bind="text:StringValue"></td>
                    <td data-bind="text:BoolValue"></td>

                </tr>
            </tbody>
        </table>
    </div>

Результат. enter image description here Не стесняйтесь, дайте мне знать, если я могу чем-то помочь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...