Aaron
Aaron

Reputation: 168

MVC Ajax Partial Render Redirecting

I am trying to redirect to a different page from my controller. However I have a dynamic partial render setup on my page which renders part of the page into a specific div.

$(document).ready(function () {
   $.ajax({
      url: '<%=Url.Content("~/Area/Controller/Action")%>';
      success: function (data) {
        $("#div1").html(data);
      },
      error: function (data) {
        $("#div1").html(data.responseText);
      }
   });
});

The issue I am getting is when I try to Redirect from the controller, the page to which I redirected to gets rendered inside the div instead of just redirecting completely.

Controller:

public ActionResult Index()
{
   if (condition...) 
      return RedirectToAction("Index", "Controller", new { Area = "Area" });

   return PartialView("view", model);
}

I need to be able to completely redirect to another page.

Upvotes: 1

Views: 1882

Answers (2)

Sagar Wagh
Sagar Wagh

Reputation: 1

Just trying to hack your logic to make it work.

public ActionResult Index()
{
   if (condition...) 
      return new {Status = 1, Content = <your URL to Redirect to>};

   return new {Status = 2, Content = PartialView("view", model)};
}



$(document).ready(function () {
   $.ajax({
      url: '<%=Url.Content("~/Area/Controller/Action")%>';
      success: function (data) {
        if(data.d.Status = 1)
          {
            window.location.href = data.d.Content;  
          }
        else
          {
            $("#div1").html(data.d.Content);
          }            
      },
      error: function (data) {
        $("#div1").html(data.responseText);
      }
   });
});

Note: I have not tested this. You may need to play with it to make it work. Also you may need to change return type of Index to 'object'.

Please let me know the result.

Upvotes: 0

hohner
hohner

Reputation: 11588

You're currently asking jQuery to fill $('#div1') with the HTML response from the controller. This is not what you want. Why doesn't your controller just send back the URL instead of the page HTML?

$.ajax({
   url: '<%=Url.Content("~/Area/Controller/Action")%>';
   success: function (data) {
      window.location.href = data.url;
   },
   error: function (data) {
      $("#div1").html(data.responseText);
   }
});

You also included an extra closing bracket which I've removed.

Upvotes: 1

Related Questions