简体   繁体   English

如何从Java脚本函数使用参数调用函数背后的代码

[英]how to call code behind function with parameter from java script function

I want to call function of .cs file from java script function. 我想从Java脚本函数调用.cs文件的函数。 From javascript function I also want to pass one parameter to code behind function. 从javascript函数,我还想将一个参数传递给函数后面的代码。 Following is code of both the files. 以下是两个文件的代码。 Thanks in advance. 提前致谢。

In demo.aspx
<script>
function getValue(id)
{
   "<%getData(id);%>"
} 
</script>

In demo.aspx.cs
public void getData(string s)
{
  //code to work on string.
}

I am getting error that is 'id' is not declare in demo.aspx file. 我收到了在demo.aspx文件中未声明的'id'错误。

You can try this in your web form with a button called btnSave for example: 您可以在Web表单中使用名为btnSave的按钮进行尝试,例如:

<input type="button" id="btnSave" onclick="javascript:SaveWithParameter('Hello User')"  value="click me"/>

<script type="text/javascript">
  function SaveWithParameter(parameter)
   {
     __doPostBack('btnSave', parameter)
   }
</script>

And in your code behind add something like that on page load 然后在您的代码后面的页面加载中添加类似内容

public void Page_Load(object sender, EventArgs e)
{
  string parameter = Request["__EVENTARGUMENT"]; // parameter
 // Request["__EVENTTARGET"]; // btnSave and do your work
}

Hope it helps 希望能帮助到你

getData is a server side method so if you want to call it from client side, one possible way is to use AJAX call and mark the method on the server as script callable. getData是服务器端方法,因此,如果要从客户端调用它,一种可能的方法是使用AJAX调用并将服务器上的方法标记为可调用脚本。

If you're using ScriptManager, once you mark your page method as WebMethod , you are able to access it from javascript using the PageMethods variable, see http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx 如果您使用的是ScriptManager,则将页面方法标记为WebMethod后 ,就可以使用PageMethods变量从javascript访问它,请参阅http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx

If you want to do this using jQuery, check this post http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ 如果要使用jQuery进行此操作,请查看此帖子http://encosia.com/using-jquery-to-direct-call-aspnet-ajax-page-methods/

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

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