views:

68

answers:

2

I have an ASP.NET MVC Form, but the data from it needs to be posted via jQuery (not ajax). It cannot be submitted using the normal model, because the Controller Action requires a JSON string, and the only way to get that string is to use jQuery's $.post method to turn the data into JSON, and then post it to the Controller.

This works fine. However the end result is that after posting, the form is supposed to Redirect to a different page (Like a Success Page). This does not occur, it just stays on the same page.

If I use return false; in my jQuery code, it will stop the form from trying to post again, but this doesn't solve my problem. I really don't want to set the URL manually, either, since I want to keep as much out of javascript as humanly possible.

Controller

    [HttpPost]
    public ActionResult Receive([FromJson] jsonObject item)
    {
        if (ModelState.IsValid)
        {
                       // logic
        }
        return RedirectToAction( ... );
    }

JavaScript

            $('.submit').click(function(e) {
                    var json = JSON.stringify(data);
                    $.post( location.href, { item: data});
            });

This submits the code right. and the return statement even gets hit if I step through it in the debugger, but it never does the redirect. What can I do?

+2  A: 

How about returning a string from your action that is the location you want to redirect to.

Then in your success callback, use the javascript redirect method by setting window.location.

E.g. NOTE: this is untested and probably doesn't work exactly like this, but you get the jist.

Controller

[HttpPost]
public ActionResult Receive([FromJson] jsonObject item)
{
    if (ModelState.IsValid)
    {
                   // logic
    }
    return Json("urltoredirectto");
}

JavaScript

$('.submit').click(function(e) {
    var json = JSON.stringify(data);
    $.post(location.href, { item: data },
        function (data) {
            window.location = data;
        });
});

HTHs,
Charles

Charlino
Why does the return not simply execute when it is hit in the first place? Why do I need to return something in javascript when I've already done it in the Controller?
Stacey
Because the response from an Ajax call doesn't go to the browser (where it would cause the redirect to happen), it instead goes to your javascript code and is swallowed since you do nothing with the results of posting.
Hightechrider
+1  A: 

Well, $.post is an ajax command so the result it receives is the redirect request. This means the browser won't receive the request because the ajax command is consuming it.

I found this that might help: Use jQuery to attach JSON to a form and submit it

Kelly Ethridge