Ajax.BeginForm with OnComplete always updates page
Asked Answered
S

1

12

I have simple ajax form in MVC. In AjaxOptions there is OnComplete set to simple javascript function which does one thing - returns false.

@using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { UpdateTargetId = "DivFormId", HttpMethod = "Post", OnComplete = "preventUpdate" }))

function preventUpdate(xhr) {
    return false;       
}

The problem is, that page is already updated. E.g. in one case controller returns partial view after postback, in other case it returns some Json object. I want it to update page when partial view is returned, and to show dialog window when json is returned. Unfortunately when json is returned, it clears the page (update it with json) even when OnComplete function returns false as MSDN says: To cancel the page update, return false from the JavaScript function.

How to prevent page update depending on received response?

Thank you!

----- UPDATE -------

So far I found following solution. When I don't specify UpdateTargetId, I can do manually with the response what I want. But it is still not documented behaviour with return false.

Shwa answered 24/9, 2012 at 10:8 Comment(2)
Perhaps this will help, also look at the first comment https://mcmap.net/q/40403/-event-preventdefault-vs-return-falseColourable
This is not the case (but to be sure, I tried also this two methods). This is MS handling for Ajax.BeginForm with events like OnBegin, OnComplete,... And OnComplete according to MSDN doc should be possible to stop by returning false.Shwa
S
23

Use OnSuccess and get rid of UpdateTargetId. Like this:

@using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "Post", OnSuccess = "foo" }))
{
    ...
}

and then:

function foo(result) {
    if (result.SomePropertyThatExistsInYourJsonObject) {
        // the server returned a JSON object => show the dialog window here
    } else {
        // the server returned a partial view => update the DOM:
        $('#DivFormId').html(result);
    }
}
Shaver answered 25/9, 2012 at 7:37 Comment(1)
In order to use Ajax.BeginForm you need the following javascript file (which does not come standard in the MVC 5 template): jquery.unobtrusive-ajax.js nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/3.2.3Graviton

© 2022 - 2024 — McMap. All rights reserved.