Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine what View is going to be rendered in @RenderBody()

In _Layout.cshtml is it possible to determine what View is going to be rendered in @RenderBody() ?

like image 306
gsharp Avatar asked Jun 19 '15 11:06

gsharp


1 Answers

You can get the View (i.e. Index.cshtml) through ((RazorView)ViewContext.View).ViewPath

Example for your needs:

<script type="text/javascript" src="~/Content/Scripts/@(Path.GetFileNameWithoutExtension(Server.MapPath(((RazorView)ViewContext.View).ViewPath))).js"></script>

If you need your actual View (i.e. _Layout.cshtml), you can use VirtualPath instead.


Old answer Reading your comments, you want to add a

<script ...>...</script>

depending on the view but outside of @RenderBody()?

Then put

@RenderSection("Scripts", required:false)

and in your view define the section like

@section Scripts {
   <script ...>...</script>
}

So you don't need to maintain your _Layout.cshtml since every View defines their own scripts.

Here is an easy explanation: http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor

like image 115
Matt Avatar answered Nov 15 '22 07:11

Matt