2

Is it possible to do a Http Post on a button from Asp.Net Web Forms which has to run an event code too?

If i do the Http Post on the button in the following way:

<input type="submit">

I willl not be able to run the code of the event, and if I add the button as an asp control, I will not be able to do the post request.

This question comes as a simpliy of this one which did not had so much success.

Community
  • 1
  • 1
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76

3 Answers3

1

You can use asp:Button which offers OnClientClick and OnClick events. OnClientClick calls the client side function. You can make an ajax call on OnClientClick and OnClick run the event.

<asp:Button ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="CallAjax()" runat="server" />

function CallAjax() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Default.aspx/CallAjax",
            data: JSON.stringify({ name: "YourNmae", age: "12" }),
            dataType: "json",
            async: false,
            success: function (data) {
                //your code

            },
            error: function (err) {
                alert(err.responseText);
            }

        });
    }
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
  • I appreciate your answer, it is really correct according to what I asked, but i couldn't use it to achieve the entire functionality I needed. But anyway, it's correct, and I want to thank you! – meJustAndrew Jun 24 '16 at 14:18
1

Add a normal <input type="button" /> and a hidden asp:button (css hidden), attach an event to normal input, then do a

__doPostBack('<%= buttonId.UniqueName %>');

In the click event, that should do it

Tawfik Khalifeh
  • 939
  • 6
  • 21
0

To solve the post problem, I have made the button which was doing the post hidden, and I have added another control which was running the event, and at the end of the event, it was using ScriptManager to register a script which was actually doing a click on the hidden button. Then the hidden button in this case is doing a simple post, as it's input type equals submit.

I needed this hidden button, because I wanted to open the result in another view, and I couldn't manage to do it in the Ajax way. More details about the implementation of this functionality, and the problems which can occur in order to achive it, can be found in this question, or in this one.

Community
  • 1
  • 1
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76