简体   繁体   中英

Call code-behind function from javascript in visual webpart

Is it even possible? To call a code-behind c# function from javascript in a visual web part?

It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.

Thanks guys..

You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.

Code behind

public partial class _Default : Page 
{
  [WebMethod]
  public static string GetDate()
  {
    return DateTime.Now.ToString();
  }
}

Javascript

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});

Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?

I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.

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