简体   繁体   English

从可视Webpart中的javascript调用代码隐藏函数

[英]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? 要在可视Web部件中从JavaScript调用C#函数背后的代码?

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. 您可以使用jQuery ajax调用服务器端方法,并获取要在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 使用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? 为什么不使用可通过AJAX调用的Web服务(启用Ajax的WCF服务)?

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. 将您的逻辑放在一个额外的类中,并在Web服务和Webpart中使用该类。 Then you cann call the Method from Code and from Javascript. 然后,您无法从代码和Java脚本调用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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