Search code examples
asp.net-mvcasp.net-mvc-4razorhtml-helperrazorgenerator

Asp.Net MVC Helper: create a global helper for loading view with or without layout


I want to create a application in which if there is Ajax call it return Partial view and if it is a page refresh it return with layout and render script. But the problem is partial view won't render sections, for that I have created a MVC helper in APP_Code as :

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

When I am calling it in my view I am getting the bellow 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 is still there, I also searched a lot but couldn't found the solution.


Solution

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

    https://stackoverflow.com/a/22977735/5179246

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

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

    The DefineSection method belongs to a WebPageBase.

    You might have to come at this from a different direction. Using partial views instead of helpers would probably fix this problem.

    You can use nested layout..The inner layout is just to render body and script.