3

Using MVC 4, I have a partial view form which contains an @Ajax.BeginForm.

The form submits as expected, and the result is displayed asynchronously in my main view.

I want a condition on my controller that if a certain parameter is true on my form, then it redirects to a whole new page (instead of displaying the result in my main view).

When I tried return RedirectToAction, the whole view displays in the div that the form normally displays in, as opposed to ignoring the AJAX and redirecting to a completely new page.

Does anyone know how I can acheive this?

alex
  • 6,818
  • 9
  • 52
  • 103
loveforfire33
  • 1,090
  • 3
  • 25
  • 46
  • @loveforfire..if you can show some code..it would be easy to understand – Sai Avinash Jan 07 '14 at 14:42
  • 2
    http://stackoverflow.com/questions/18667447/return-partial-view-and-json-from-asp-net-mvc-action the redirect has to happen on the view side. pass the variable through with the ajax call and if its true do a window.location – Matt Bodily Jan 07 '14 at 14:42
  • If the decision parameter is available to the client, then I would control the partial vs reload behaviour from the client, i.e. redirect instead of ajax if `parameter == true`. – StuartLC Jan 07 '14 at 14:44

2 Answers2

7

You can use return JavaScript to achieve it.

public ActionResult MyAction()
{
    if (parameter)
    {
        return JavaScript("window.location = '" + Url.Action("Action", "Controller") + "'");
    }
    //Do something here
    return PartialView("ParitalView", Model);
}
Lin
  • 15,078
  • 4
  • 47
  • 49
2

You could not perform RedirectToAction in a ajax call.

Just return a HttpStatusCodeResult and based on it perform redirect in Javascript

public ActionResult Save()
{

   return new HttpStatusCodeResult(302,
            "/Users/Details");
}

In Ajax Error function, set in AjaxOptions { OnFailure = "Error" }

function Error(response, status, error) {
    window.location.href= response.statusText;
}
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120