[英]Load Javascript from a Partial View in ASP.NET MVC3
I have an ASP.NET MVC3 application in C# and Razor. 我在C#和Razor中有一个ASP.NET MVC3应用程序。
I use the standard _Layout.cshtml
from the MVC3 application template in VS2010. 我使用VS2010中MVC3应用程序模板中的标准
_Layout.cshtml
。 I would like to add Javascript code in one of my Partial View
just when the View
is rendered and not attach the Javascript directly in the _Layout
. 我想在我的一个补充Javascript代码
Partial View
正当View
呈现,而不是在直接附加的JavaScript _Layout
。
My View
looks like this: 我的
View
如下所示:
@model MyNameSpace.ViewModels.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Filters</legend>
@{ Html.RenderPartial("Filters", Model.Filters); }
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
And my Partial View
Filters.cshtml
looks like this: 我的
Partial View
Filters.cshtml
如下所示:
@model MyNameSpace.ViewModels.FiltersViewModel
<p>
@Html.DropDownListFor(
x => x.Type,
new SelectList(Model.Types, "Value", "Text"),
"-- select type --"
)
</p>
<p>
@Html.DropDownListFor(
x => x.Category,
new SelectList(Model.Categories, "Value", "Text"),
"-- select category --"
)</p>
<script type="text/javascript">
//Some Javascript
</script>
If I leave the View
like this, the Javascript is rendered inside the <body>
and it looks very ugly. 如果我这样离开
View
,则Javascript会在<body>
内部呈现,并且看起来非常难看。 I can add the Javascript directly in the <head>
section of the _Layout but it is not what I want. 我可以直接在_Layout的
<head>
部分中添加Javascript,但这不是我想要的。 How can I achieve my purpose? 我怎样才能达到目的?
add @RenderSection("HeadContent", required: false)
inside your main layout (masterpage) and then add something like 在您的主布局(
@RenderSection("HeadContent", required: false)
添加@RenderSection("HeadContent", required: false)
),然后添加类似
@section HeadContent {
<link href="@Url.Content("~/Content/styles/admin.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
}
in your partial view 在您的局部视图中
When razor will compiling html page it will place content from @section block from the partial view to the place where you put @RenderSection("HeadContent", required: false) on the layout (masterpage). 当razor编译html页面时,它将把@section块中的内容从局部视图放到您在布局(母版页)上放置@RenderSection(“ HeadContent”,required:false)的地方。 If there are no @section block on the partial view, then nothing will be added.
如果局部视图上没有@section块,则不会添加任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.