Asp.Net MVC Helper: create global helper to load view with or without layout

I want to create an application where, if there is an Ajax call, it returns a Partial view, and if it refreshes the page, it returns with a layout and render script. But the problem in the partial view will not display the sections, for which I created the MVC helper in APP_Code as:

 @helper AddSection(Func<object, object> content)
 {
   if (IsAjaxRequest)
   {
        @content(null);
   }
   else
   {
        @section scripts {
            @content(null);
        }
   }
}

      

When I find it in my view, I get the following error:

CS0103: The name 'DefineSection' does not exist in the current context
Line 71: #line hidden
Line 72: DefineSection("scripts", () => {
Line 73: 

      

I tried many things but this error still exists, I also searched a lot but couldn't find a solution.

+3


source to share


2 answers


I searched a lot and found that the section inside the helper is not possible. below link:

fooobar.com/questions/1535852 / ...

The @helper and @section syntax are special directives for compiling pages.

A HelperResult (helper) doesn't know how to define the section.



DefineSection method belongs to WebPageBase.

You may have to go from a different direction to it. Using partial views instead of helpers will probably fix this problem.

You can use nested layout. Inner layout is just to do body and script.

+3


source


You can check the request header (as described in the question ). Check X-Requested-With

if it says XMLHttpRequest

it should be an XHR (Ajax) request.

In your controller, you can return PartialView

in the same method.

public ActionResult YourAction()
{
    Boolean IsAjax = false; //check the request header

    if (IsAjax) 
    {
        ViewBag.UseLayout = false;
        return PartialView("PartialView");
    }
    else
    {
        return View("View");
    }
}

      



Inside your view, you can read ViewBag.UseLayout

and decide to make a complete layout with all sections or not:

@{
    if (ViewBag.UseLayout == null || ViewBag.UseLayout) {
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    else {
        Layout = null;
    }
}

      

You can extend it to ViewStart.cshtml

, with a null check of the ViewBag, so that this applies to all views.

0


source







All Articles