-1

I have a variable whose value I calculate in JavaScript. I want to pass that variable to C# to delete a record in the database. This is the code I'm using right now:

<div>
    <h4>Example 2</h4>
    <div class="indent">
        <p class="center"><img src="assets/ex2.jpg" /></p>
        <p class="right">
            <button onclick='
                $.msgbox("Are you sure that you want to permanently delete the selected element?",
                    {
                        type: "confirm",
                        buttons : [
                            {type: "submit", value: "Yes"},
                            {type: "submit", value: "No"},
                            {type: "cancel", value: "Cancel"}
                        ]
                    }, 
                    function(result) { 
                        $("#result2").text(result); 
                    } 
                );
            '>
                Example 2
            </button>
            <input id="inpHide" type="hidden" runat="server" />  
            <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
            Result: <span id="result2"></span>
    </div>

How do I pass the variable from JavaScript to C#?

1
  • This question depends a lot on your framework. If this is MVC, you might create a controller or Web API, then do a AJAX POST to it. If this is some other web tech, you may do a Web Service, Page Method, etc. Commented Jul 21, 2013 at 0:04

2 Answers 2

0

You can easily do this by using hidden field. Set the value of the hidden field through the jquery code and fetch the hidden field value through the server side code c#

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to change my code or give an example please?
0
  1. you need to first change the button to the server side so you can add access server code like the one below:

    < asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" onClientClick="Your javascript code" />
    
  2. you can add the javascript in onClientClick event

  3. Add the value of the variable to hidden field.. adding

    $("#inpHide").val(result); 
    

3 Comments

And why exactly are you posting two different answers?
When giving answer it is not quite clean and clear in the comment with code
Thanks for the answer would have to replace $ ("# result2"). Text (result); than $ ("# inpHide"). Val (result); Use

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.