简体   繁体   中英

how to call code behind function with parameter from java script function

I want to call function of .cs file from java script function. From javascript function I also want to pass one parameter to code behind function. 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.

You can try this in your web form with a button called btnSave for example:

<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.

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

If you want to do this using jQuery, check this post http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

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