Download PartialView for AJAX and View for a request other than AJAX

I want to implement something like facebook:

  • after left-clicking on a photo, it loads via AJAX
  • after a middle click on the scroll, it usually loads with an additional layout

Now I have a view that loads into the controller in two different ways:

public ActionResult Overview() { return View("Overview"); } public ActionResult OverviewPartialView() { return PartialView("Overview"); } 

And in the jquery script it looks like this:

 $(contentContainer).load(_link + 'PartialView'); 

My question is, is there a better way to solve this problem? I tried something like this in _ViewStart:

 @{ Layout = "~/Views/Shared/_Layout.cshtml"; if (IsAjax) { Layout = null; } } 

And something like this in the controller:

 public ActionResult Index() { if (Request.IsAjaxRequest()) return PartialView(); return View(); } 

But in those solutions, I had a cache problem, after opening the page with the layout, the page with the layout was also loaded in the AJAX request.

+4
source share
2 answers

You can use one action:

 public ActionResult Overview() { return View(); } 

and inside _ViewStart.cshtml :

 @{ Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/Layout.cshtml"; } 

Another possibility is as follows:

 public ActionResult Overview() { if (Request.IsAjaxRequest()) { return PartialView(); } return View(); } 

then if you want to avoid caching problems, you can use the POST request instead of GET:

 $.post(_link, function(result) { $(contentContainer).html(result); }); 

or use $.ajax with GET and specify cache: false , which will add a unique query string parameter to avoid browsers caching:

 $.ajax({ url: _link, type: 'GET', cache: false, success: function(result) { $(contentContainer).html(result); } }); 
+9
source

You can use a semi-global solution with ActionFilter. This example converts the original ViewResult to PartialViewResult if the request is AJAX (XHR)

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AjaxifyFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { if(!filterContext.HttpContext.Request.IsAjaxRequest() || !(filterContext.Result is ViewResult)) return; var view = filterContext.Result as ViewResult; filterContext.Result = new PartialViewResult { TempData = view.TempData, ViewData = view.ViewData, ViewName = view.ViewName, ViewEngineCollection = view.ViewEngineCollection }; } } 
+2
source

All Articles