简体   繁体   中英

Can't render section with script in a partial view in Razor

I've seen a cool gadget and I want to use it on my page. I've chosen all the options and they produced a JS that I'm supposed to execute from my site.

Since I'm using Razor, I need to render it as a section so I've added one. However, as I attempted to render it, I got error message telling me that:

The file "~/Views/Home/EyeCandy.cshtml" cannot be requested directly because it calls the "RenderSection" method.

So I've googled and found a bunch of articles explaining how to resolve it. The best one (after a few hours) is this particular reply . However, I just can't wire my head around it and get confused.

@{ Layout = "~/Views/Shared/_Default.cshtml"; }
@model List<Donkey>
<h1>List of the eye candies.</h1>

@RenderSection("Footie", false)
@section Footie { <script src="@Url.Content("...")" 
                   async="async" 
                   type="text/javascript"></script> }

In the linked reply, there are three files.

  1. _PartialScripts.cshtml , which I don't have and will need to add populating it from the script tag in my section Footie .
  2. _Partial.cshtml , which is my current view called EyeCandy.cshtml .
  3. The unnamed code snippet, which I understand corresponds to my _Default.cshtml layout.

Now, in my head, it doesn't make sense, because the point is to keep the script out of the layout and limit its scope to the one view where I test my eye candies. I'm sure I'm just too slow to get it at this stage but if someone, pretty-pretty please, points out what I missunderstood, I'll be so happy.

You need to call the @RenderSection("Footie", false) in your layout, not in your specific view.

So add this to your ~/Views/Shared/_Default.cshtml

@RenderSection("Footie", false)

And in your specific view, you can execute your custom code, which is wrapped inside the Footie section

@section Footie { 
  <script src="@Url.Content("...")" async="async" type="text/javascript"></script> 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM