问题描述
正如标题所述,我想在局部视图中定义一个部分.
As the title states, I want to define a section in a partial view.
我测试过的代码如下:
控制器:
public ActionResult Test()
{
return View();
}
public ActionResult PartialTest()
{
return PartialView("_PartialTest");
}
Test.cshtml:
Test.cshtml:
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
@Html.Action("PartialTest")
_PartialTest.cshtml:
_PartialTest.cshtml:
<p>partial Test</p>
@section scripts {
<script type="text/javascript">
$(document).ready(function() {
alert("Test");
});
</script>
}
将 scripts
部分放在 Test.cshtml 中工作正常,因此问题不在布局中.
Placing the section scripts
in the Test.cshtml works fine so the problem isn't in the layout.
有人知道怎么做吗?
推荐答案
部分视图不支持 @section
标签.您应该将它们添加到引用局部视图的视图中.有关更多信息,请参阅此问题:使用 Razor 视图引擎将内容从部分视图 ASP.NET MVC 3 注入特定部分.
Partial views don't support @section
tag. You should add them in the view which references the partial view. See this question for more information: Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine.
这基本上归结为这样一个事实,即引用局部视图的主视图应该负责包含 Javascript,而不是局部视图本身.
It basically comes down to the fact that the main view referencing a partial should be responsible for including Javascript, not the partial view itself.
这篇关于ASP MVC 在局部视图中定义部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!