1

How do you run JavaScript after a Form has been successfully posted and returned?

<% Html.BeginForm(); %>
....
<% Html.EndForm(); %>
4
  • Do you have multiple forms in this page .. is it posting to some other page .. ? could you plz give more info .. thanks Commented Nov 18, 2009 at 21:16
  • It is a shade vague, so the form has posted, the HTTP POST has been received and processed by the controller which then returns a view - is that when you want to execute JavaScript? Commented Nov 18, 2009 at 21:28
  • you need to be more precise, you mean like a post-backs in asp webforms, if you round your JavaScript code within a function, you can call it will, and not auto-executed on document ready. Commented Nov 18, 2009 at 21:44
  • Thanks all for the help, sorry for not being absolutely clear. will work on that in the future. Commented Nov 23, 2009 at 13:31

4 Answers 4

1

I post most of my forms asynchronously, using JQuery's ajax function. When the page I posted to processes the post, it returns some JSON, which my original posting javascript reads (as a success callback), and then makes a decision what to do. This is the way most web apps are being written these days, you're alternative is to redirect to some page that has an embedded script block.

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

Comments

1

If you are posting back via jQuery there is a Success attribute in which you can put jScript to run a function.

$.ajax({
  type: "POST",
  url: "MyPage.aspx/jQueryDoStuff",
  data: "",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  async: false,
  success: function(msg) {
    DoPostAjaxStuffHere(msg);
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) { }
});

Also note the Error attribute which can be handy also.

Comments

1

In a traditional (non-ajax) POST you are getting a new page back, so javascript will be run the same way you would on any other page.

If you are asking how do you POST and reuse the same view as a GET and run javascript only on the POST, than the short answer is you don't. You will want to use a different view for the POST that has the additional javascript that needs to be run. You can reuse most of your view code through partial page views.

Comments

0

For async forms, look at this one. There're several callbacks available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.