C# ASP MVC 在局部视图中定义部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17876538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:43:19  来源:igfitidea点击:

ASP MVC Define Section in Partial View

c#asp.net-mvcasp.net-mvc-4asp.net-mvc-partialview

提问by Jeandre Pentz

As the title states, I want to define a section in a partial view.

正如标题所述,我想在局部视图中定义一个部分。

My code that I've tested with are as follows:

我测试过的代码如下:

Controller:

控制器:

public ActionResult Test()
{
    return View();
}

public ActionResult PartialTest()
{
    return PartialView("_PartialTest");
}

Test.cshtml:

测试.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>
}

Placing the section scriptsin the Test.cshtml works fine so the problem isn't in the layout.

将该部分scripts放在 Test.cshtml 中工作正常,因此问题不在布局中。

Anyone know how to do this?

有人知道怎么做吗?

采纳答案by Henk Mollema

Partial views don't support @sectiontag. 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.

部分视图不支持@section标签。您应该将它们添加到引用局部视图的视图中。有关更多信息,请参阅此问题:Injecting content from a partial view ASP.NET MVC 3 with Razor View Engine

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.

它基本上归结为这样一个事实,即引用局部视图的主视图应该负责包含 Javascript,而不是局部视图本身。

回答by k1234

I know this question is super out-dated, but for anyone out there who might still wondering (as I was):

我知道这个问题已经过时了,但是对于那些可能仍然想知道的人(就像我一样):

You can actually get around this problem by changing the @section scripts { }portion in your partial views to this:

您实际上可以通过将@section scripts { }部分视图中的部分更改为以下内容来解决此问题:

@using (Html.BeginScriptContext())
{
    Html.AddScriptBlock(
        @<script type="text/javascript">
        //rest of script
    );
}

This will allow you to have a script in your partial view and achieve that widget-like structure. Hope this helps!

这将允许您在局部视图中有一个脚本并实现类似小部件的结构。希望这可以帮助!