简体   繁体   中英

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript

<script type="text/javascript">
    $(document).ready(function () {

        $("#some_id").click(function () {
            var id = document.getElementById('HiddenField2');
            var a = <%=btn_Click(id)%>;
        });

    });
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
 public string btn_Click(String item_id)
    {
        /*do some thing*/

        return null;
    }  

But this piece of code always giving me error of context. That id is not defined in this context. Can some please let me know what wrong i am doing?

First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.

Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value .

Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click .

The button click event in C# will be triggered by Postback when your browser post data back to asp.net I do not understand why you use HiddenField here,so my suggestion do not consider about it

Solution 1: first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js

sample code is here

Solution 2: if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too

In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

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