简体   繁体   中英

How can I call a server side c# method via javascript without a WebMethod or Updatepanel?

I would prefer not to use an update panel and using the common WebMethod approach leads me to this error with this code

     private string currentHtml() {
         StringWriter str_wrt = new StringWriter();
         HtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);
         Page.RenderControl(html_wrt);
         return str_wrt.ToString();
     }

     [WebMethod]
     public static void EmailPtoRequest() {
         string test = currentHtml();
     }

Error 8 An object reference is required for the non-static field, method, or property 'PtoRequest.cs.WebForm1.currentHtml()

Clearly the method being static is causing a bunch of headaches.

Is there a standard that I can use for this type of functionality? The goal is to allow the user to send their data to the server without causing a post and refreshing the page.

Note: I DO NOT want to use a webmethod as it is causing an error which does not let me compile.

     public partial class WebForm1 : System.Web.UI.Page {
     protected void Page_Load(object sender, EventArgs e) {

     }

     private string currentHtml() {
         StringWriter str_wrt = new StringWriter();
         HtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);
         Page.RenderControl(html_wrt);
         return str_wrt.ToString();
     }

     [WebMethod]
     public static void EmailPtoRequest() {
         WebForm1 WebForm1 = new WebForm1();
         string test = WebForm1.currentHtml();
     }
 }

Results in 'test' being an empty string instead of the html of the page.

   private static string currentHtml() {
         StringWriter str_wrt = new StringWriter();
         HtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);
         Page.RenderControl(html_wrt);
         return str_wrt.ToString();
     }

     [WebMethod]
     public static void EmailPtoRequest() {
         string test = currentHtml();
     }
 }

Results in the first error again, but in the currentHtml method instead.

Please remember the question is not about the error, but an alternative to webmethod or update panels. Thank you.

3 options:

  1. Make the currentHtml method static,

  2. Instantiate the class that contains currentHtml like this:

    new MyClass().currentHtml();

  3. Use an ajax enabled wcf service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM