Accessing a common variable in WebMethod and jQuery

有些话、适合烂在心里 提交于 2019-12-24 10:46:27

问题


In my ASP.Net page, I am loading data from server while scrolling using jQuery AJAX. I am using this method since loading data from the server using AJAX will help any application in improving its performance because data which is displayed on the screen alone is loaded the first time and more data, if required, will get loaded from the server as the user scrolls. I am using the following code:

$(document).ready(

        function () {
            $contentLoadTriggered = false;
            $(window).scroll(

            function () {
                if ($(window).scrollTop() >= ($("#wrapperDiv").height() - $(window).height()) && $contentLoadTriggered == false) { //here I want to check for the isReady variable in ViewState
                    $contentLoadTriggered = true;
                    $.ajax({
                        type: "POST",
                        url: "MyPage.aspx/GetDataFromServer",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: true,
                        cache: false,
                        success: function (msg) {
                            $("#wrapperDiv").append(msg.d);
                            $contentLoadTriggered = false;
                        },
                        error: function (x, e) {
                            alert("The call to the server side failed. " + x.responseText);
                        }
                    });
                }
            });
        });

[WebMethod]
public static string GetDataFromServer()
{
    string resp = string.Empty;
    for (int i = 1; i <= 10; i++)
    {
        resp += "<p><span>" + i + "</span> This content is dynamically appended to the existing content on scrolling.</p>";
    }

    //if (myConidition)
        //ViewState["isReady"] = true;

    return resp;
}

At some point (when my condition is met), I want to stop loading data from the server. So I thought about setting a boolean variable isReady in the ViewState and then check the value of this variable in jQuery to determine whether or not to call the WebMethod. Unfortunately, I can't use ViewState in WebServices and I also don't know how to access ViewState in jQuery.

What can I use as an alternative to ViewState, which can be accessed from both the WebMethod and the jQuery?


回答1:


The best way i can think of is to send a custom class object or string [];

Public class CustomClass
{
    public string HTML { get; set; }
    public bool Load  { get; set; }
}

[WebMethod()]
public static StatusViewModel  GetDataFromServer()
{
    // do work
    return CustomObject;
}

Hope it helps.



来源:https://stackoverflow.com/questions/10329492/accessing-a-common-variable-in-webmethod-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!