I am learning about Progressive Enhancement and I have a question about AJAXifying views. In my MVC 3 project I have a layout page, a viewstart page, and two plain views.
Just put the following code on the top of the page
@{
Layout = "";
}
You don't have to create an empty view for this.
In the controller:
if (Request.IsAjaxRequest())
return PartialView();
else
return View();
returning a PartialViewResult will override the layout definition when rendering the respons.
Create two layout: 1. empty layout, 2 . main layout and then write in _viewStart file this code:
@{
if (Request.IsAjaxRequest())
{
Layout = "~/Areas/Dashboard/Views/Shared/_emptyLayout.cshtml";
}
else
{
Layout = "~/Areas/Dashboard/Views/Shared/_Layout.cshtml";
}}
of course, maybe it is not best solution
For a Ruby on Rails application, I was able to prevent a layout from loading by specifying
render layout: false
in the controller action that I wanted to respond with ajax html.
I prefer, and use, your #1 option. I don't like #2 because to me View()
implies you are returning an entire page. It should be a fully fleshed out and valid HTML page once the view engine is done with it. PartialView()
was created to return arbitrary chunks of HTML.
I don't think it's a big deal to have a view that just calls a partial. It's still DRY, and allows you to use the logic of the partial in two scenarios.
Many people dislike fragmenting their action's call paths with Request.IsAjaxRequest()
, and I can appreciate that. But IMO, if all you are doing is deciding whether to call View()
or PartialView()
then the branch is not a big deal and is easy to maintain (and test). If you find yourself using IsAjaxRequest()
to determine large portions of how your action plays out, then making a separate AJAX action is probably better.
With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request
Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs
using System;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class HttpRequestExtensions
{
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
}
I searched for a while now on this and hope that will help some others too ;)
Resource: https://github.com/aspnet/AspNetCore/issues/2729