Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.BeginForm with OnComplete always updates page

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.

like image 605
Jozef Krchňavý Avatar asked Sep 24 '12 10:09

Jozef Krchňavý


1 Answers

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);
    }
}
like image 108
Darin Dimitrov Avatar answered Nov 16 '22 00:11

Darin Dimitrov