在Web form中静电中调用非静态方法

发布于 2025-02-08 07:51:12 字数 350 浏览 0 评论 0原文

我正在尝试从客户端进行AJAX调用,该调用loadNotifications()方法在客户端中使用中继器进行某些数据指标

是否有一种方法可以在静态Web方法内调用方法而不创建对象,因为创建了新对象WebForm使所有控件都无效

,或者有没有办法在内存中找到页面的创建对象并使用其中的方法?

[WebMethod]
public static void LoadTheNotifications()
{
    var camDash = new CameraDashboard();
    camDash.LoadNotifications();

    //LoadNotifications();
}

I am trying to make ajax call from client side that calls the LoadNotifications() method which does some databinding with a repeater in the client side

is there a method to call a method inside the static web method without creating the object because creating new object of the webform makes all controls null

or is there a way to find the created object of the page in the memory and use the methods inside it?

[WebMethod]
public static void LoadTheNotifications()
{
    var camDash = new CameraDashboard();
    camDash.LoadNotifications();

    //LoadNotifications();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笨死的猪 2025-02-15 07:51:12

不幸的是,您无法做到这一点。

请记住,一旦网页运行了后面的代码,就会呈现网页,然后将其发送到客户端。在服务器上,该代码,该类,变量,网页被扔在垃圾桶中。它不再存在了。 Web服务器现在只是坐在那里等待任何用户 - 您不必将整页发布回服务器。

因此,当您进行Ajax调用时,没有页面帖子,并且实际上页面不重新定位,所有网页控件,代码变量,甚至页面加载事件都不存在,不要开火,不能使用。您必须掌握页面往返的概念。一旦将页面发送到客户端,服务器端代码,类,代码变量以及所有内容都倾倒到垃圾桶中。

该服务器不会跟踪跟踪或保留每个网页的实例。一台服务器会从所有用户中处理并将处理网页,而不仅仅是您的网页。

您也可能会像称呼独立的子例程一样。子例程退出后,该子例程中的值和代码消失了,并且范围不超出范围。

调用静态方法也是如此。除非您有一个页面帖子,否则您将无法使用任何其他方法。控件等的值坐在您的桌面上 - 而不是服务器端。它对您的网页一无所知 - 您可以关闭浏览器,也可以关闭计算机 - 服务器不知道,也不关心,也不在乎,它也已加载了内存中的网页 - 它已经消失了!!

因此,一些解决方案。

好吧,从客户端传递您需要的值。

说,我有两个文本框,名字,姓氏,我想打一个Ajax调用以将结果组合起来,然后将结果放入第三个文本框中。

我无法触摸网页(坐在您的桌面上)控件,因此您这样做 - 您可以将信息传递给该网络方法。

因此,说此标记:

    <div>

        Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
        <br />
        Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
        <br />
        <asp:Button ID="cmdCombine" runat="server" Text="ajax combine" CssClass="btn" 
            OnClientClick="mycombine();return false;" />

        <br />
        Full name result: 
        <asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

        <script>

            function mycombine() {

                MyFirstName = $("#txtFirst").val()
                MyLastName = $("#txtLast").val()
                
                $.ajax({
                    type: "POST",
                    url: "AjaxTest2.aspx/CombineName",
                    data: JSON.stringify({ FirstName: MyFirstName, LastName: MyLastName}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                        success: function (myresult) {
                        // put result of method call into txtResult
                        // ajax data is ALWAYS ".d" - its a asp.net thing!!!
                        $("#txtFullName").val(myresult.d)
                    },
                    error: function (xhr, status, error) {
                        var errorMessage = xhr.status + ': ' + xhr.statusText
                        alert('Error - ' + errorMessage)
                    }
                });
            }
        </script>
    </div>

然后,当我们运行时,我们得到了:

“在此处输入图像说明”

所以,我们确实得到了名字,我们确实得到了姓氏,我们确实将结果推到了全名中控制。

但是,Web方法就是这样:

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod()]
    public static string CombineName(string FirstName, string LastName)
    {
        string MyResult = "";
        MyResult = FirstName + " " + LastName;
        return MyResult;
    }

因此,您可以获取并获取控件值并将其传递给该Web方法。

另一种方式?好吧,您可以放入更新面板。这些所谓的面板可让您仅发布页面的位和部分。因此,没有出现完整的后背部,但实际上我们称之为部分页面帖子。它们也许是Web表单中最惊人的功能。

因此,代替了Ajax呼叫,不想重新订票和后返还?

放入脚本管理器,更新面板,然后将所有内容和控件和按钮移入该更新面板中。

您现在转储JavaScript,转储Web方法,然后获得此代码:

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void cmdCombine_Click(object sender, EventArgs e)
    {
        txtFullName.Text = txtFirst.Text + " " + txtLast.Text;
    }

标记现在将是:

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

            Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            <asp:Button ID="cmdCombine" runat="server" Text="combine first and last" CssClass="btn" OnClick="cmdCombine_Click" 
                 />

            <br />
            Full name result: 
            <asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

            </ContentTemplate>
        </asp:UpdatePanel>
        

页面看起来相同,但是现在您不必连接Ajax呼叫,不必连接电线介绍一个Web方法,您的代码可以自由地使用更新面板内部的控件。

您现在注意到,只有页面更新的那一部分,您会注意到您看不到完整的后背部,实际上您甚至没有看到Brwosere“ Wait/Spinner”出现。

请记住,虽然这既光滑又容易?

您的页面加载事件每次都会发射,但是再说一次,我始终创建的最后200+网页,但始终在“超越无与伦比的代码”页面内部设置代码内部的页面内部的内部装置,

if (!IsPostBack) 
{
   // my REAL page load code, and my REAL first page setup code
   // goes here
}

请考虑一个更新面板 - 它们是纯魔法。因此,将所需的控件和内容放在该面板内 - 包括按钮点击等。您可以自由修改内部的控件。

请注意,常规代码和常规全页帖子背面没有影响,此类代码已充分利用所有控件 - 包括更新面板内部的控件。

You unfortantly cannot do this.

Remember, once the web page runs the code behind, renders the web page, it is THEN sent down to the client side. On the server, that code, that class, the variables, the web page is tossed in the garbage can. It does NOT exist anymore. The web server is now just sitting there waiting for ANY user - not necessary you to post a whole page back to the server.

So, when you do a ajax call, there is no page post back, and in fact the page class is not re-initialized, and all the web page controls, the code variables, and even the page load events don't exist, don't fire, and can't be used. You have to grasp the concept of a page round trip. Once the page is sent to the client, the server side code, the class, the code variables and EVERYTHING is dumped into the garbage can.

The server does not keep track or keep a instance of each web page. That ONE server takes and will process web pages from ALL of your users - not just YOUR web page.

You might as well of this like calling a stand alone sub routine. After the subroutine exits, the values and code in that subroutine is gone, and goes out of scope.

Same goes for calling static methods. And you can't use any other methods UNLESS you have a page post back. The value of the controls etc. are sitting on your desktop - not the server side. It knows nothing about your web page - you can close the browser, or turn off your computer - the server don't know, and does not care, nor does it have the web page loaded in memory -- it is LONG gone!!

So, some solutions.

Well, pass the values you need from client side.

Say, I have two text box, first name, last name, and I want to do a ajax call to combine first and last, and put the results into a 3rd text box.

I can't touch the web page (sitting on your desktop) controls, so you do it this way - you GET and PASS the information to that web method.

So, say this markup:

    <div>

        Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
        <br />
        Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
        <br />
        <asp:Button ID="cmdCombine" runat="server" Text="ajax combine" CssClass="btn" 
            OnClientClick="mycombine();return false;" />

        <br />
        Full name result: 
        <asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

        <script>

            function mycombine() {

                MyFirstName = $("#txtFirst").val()
                MyLastName = $("#txtLast").val()
                
                $.ajax({
                    type: "POST",
                    url: "AjaxTest2.aspx/CombineName",
                    data: JSON.stringify({ FirstName: MyFirstName, LastName: MyLastName}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                        success: function (myresult) {
                        // put result of method call into txtResult
                        // ajax data is ALWAYS ".d" - its a asp.net thing!!!
                        $("#txtFullName").val(myresult.d)
                    },
                    error: function (xhr, status, error) {
                        var errorMessage = xhr.status + ': ' + xhr.statusText
                        alert('Error - ' + errorMessage)
                    }
                });
            }
        </script>
    </div>

and then when we run, we get this:

enter image description here

So, we did get the first name, we did get the last name, and we did shove the results into the full name control.

but, the web method was this:

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod()]
    public static string CombineName(string FirstName, string LastName)
    {
        string MyResult = "";
        MyResult = FirstName + " " + LastName;
        return MyResult;
    }

So, you can get and grab values of controls and pass them to that web method.

The other way? Well, you can drop in a update panel. These so called panels allow you to post back ONLY the bits and parts of the page. So, no full page post-back occures, but in fact what we call a partial page post back. They are perhaps the most amazing feature of web forms.

So, in place of that ajax call, and not wanting a full page re-fresh and post-back?

Drop in the script manager, a update panel, and move all the stuff and controls and button inside of that update panel.

You now dump the JavaScript, dump the web method, and you get this code:

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void cmdCombine_Click(object sender, EventArgs e)
    {
        txtFullName.Text = txtFirst.Text + " " + txtLast.Text;
    }

and the markup will now be this:

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

            Enter First Name: <asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            Enter First Name: <asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static"></asp:TextBox>
            <br />
            <asp:Button ID="cmdCombine" runat="server" Text="combine first and last" CssClass="btn" OnClick="cmdCombine_Click" 
                 />

            <br />
            Full name result: 
            <asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static"></asp:TextBox>

            </ContentTemplate>
        </asp:UpdatePanel>
        

The page will look the same, but now you did not have to wire up a ajax call, did not have to wire up a web method, and your code behind can freely use the controls INSIDE of the update panel.

You note now that ONLY that part of the page updates, you note that you don't see a full post-back, and in fact you not even see the brwosere "wait/spinner" occur at all.

Do keep in mind that while this is beyond slick and easy?

Your page load event DOES fire each time, but then again, the last 200+ web pages I created ALWAYS but ALWAYS has setup code inside the super beyond improant code stub inside of page load that does this:

if (!IsPostBack) 
{
   // my REAL page load code, and my REAL first page setup code
   // goes here
}

So consider a update panel - they are pure magic. So, put the controls and stuff you need inside of that panel - including the button click etc. You are free to modify ONLY the controls inside.

Note that regular code and regular full page post backs are not effected, and such code has full use of all controls - including the controls inside of the update panel .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文