如何接取在ASP.net一个静态方法内部页面控件 [英] How to acess page controls inside a static method in ASP.net

查看:1228
本文介绍了如何接取在ASP.net一个静态方法内部页面控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我呼吁背后使用jQuery使用静态Web方式方法的code。该Web方法调用是成功的,但是当试图访问一个文本框控件它给错误。一个对象引用是所必需的非静态字段,方法或属性

  [的WebMethod]
公共静态SAVEDATA()
 {
     // code插入数据DB     //插入数据成功后我需要改变文本框的文字像以下。
      txtStatus.Text =数据接收;
 }


解决方案

您可以访问诸如页面控件
<一href=\"http://stackoverflow.com/questions/14684974/asp-net-access-a-control-from-static-function\">asp.net从静态函数访问控制

 公共静态无效SAVEDATA()
{
    如果(HttpContext.Current!= NULL)
    {
        一页一页=(页)HttpContext.Current.Handler;
        文本框TextBox1中=(文本框)page.FindControl(TextBox1中);        文本框TextBox2中=(文本框)page.FindControl(TextBox2中);
    }
}

以上方法是寻找控制值。
的[的WebMethod] S整点是,他们不运行ASP.Net页面生命周期。这样一来,他们速度快,可并行。
您的控件不存在。

相反,你应该使用JavaScript(更好),或一个UpdatePanel(差)。

你的问题是如何获得静态方法

I have called a Code behind method using jQuery using Static web Method. That web method call was success but when tried to access a text box control it is giving error. An object reference is required for the non-static field, method, or property

[WebMethod]    
public static Savedata()
 {
     //code to insert data to DB

     //after inserting data successfully i need to change the text box text like following.        
      txtStatus.Text="Data Received";   
 }

解决方案

you can access page controls like asp.net access a control from static function

public static void Savedata()
{
    if (HttpContext.Current != null)
    {
        Page page = (Page)HttpContext.Current.Handler;
        TextBox TextBox1 = (TextBox)page.FindControl("TextBox1");

        TextBox TextBox2 = (TextBox)page.FindControl("TextBox2");
    }
}

Above method is for finding the control values. The whole point of [WebMethod]s is that they don't run the ASP.Net page lifecycle. This way, they're fast and parallelizable. Your controls don't exist.

Instead, you should use Javascript (better) or an UpdatePanel (worse).

your question is duplicate of How to get controls in static method

这篇关于如何接取在ASP.net一个静态方法内部页面控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆