我在我的_Layout.cshtml中定义了这个部分

@RenderSection("Scripts", false)

我可以很容易地从视图中使用它:

@section Scripts { 
    @*Stuff comes here*@
}

我正在努力解决的问题是如何从局部视图将一些内容注入到这个部分中。

让我们假设这是我的视图页面:

@section Scripts { 

    <script>
        //code comes here
    </script>
}

<div>
    poo bar poo
</div>

<div>
  @Html.Partial("_myPartial")
</div>

我需要在脚本部分中从_myPartial partial视图中注入一些内容。

我该怎么做呢?


当前回答

假设您有一个称为_contact的部分视图。Cshtml,您的联系人可以是合法的(姓名)或物理主体(名,姓)。你的视图应该关心被渲染的内容,这可以用javascript实现。所以延迟渲染和JS内部视图可能需要。

我认为唯一可以忽略它的方法是,当我们创建一种不引人注目的方式来处理这种UI关注点时。

还要注意MVC 6将有一个所谓的视图组件,甚至MVC未来也有一些类似的东西,Telerik也支持这样的东西…

其他回答

我用这个方法解决了类似的问题:

@section ***{
@RenderSection("****", required: false)
}

我想这是一种很好的注射方式。

这是一个很常见的问题,所以我会把我的答案贴出来。

我也遇到过同样的问题,虽然它不是理想的,但我认为它实际上工作得很好,并且不使部分依赖于视图。

我的场景是,一个动作本身是可访问的,但也可以嵌入到一个视图中——一个谷歌映射。

在我的_layout中我有:

@RenderSection("body_scripts", false)

在我的索引视图中有:

@Html.Partial("Clients")
@section body_scripts
{
    @Html.Partial("Clients_Scripts")
}

在我的客户视图中,我有(所有的地图和assoc。html):

@section body_scripts
{
    @Html.Partial("Clients_Scripts")
}

我的Clients_Scripts视图包含要呈现到页面上的javascript。

通过这种方式,我的脚本是隔离的,并且可以在需要的地方呈现到页面中,而body_scripts标记只在razor视图引擎第一次发现它时呈现。

这让我把所有东西都分开了——这对我来说是一个很好的解决方案,其他人可能有问题,但它确实修补了“设计”的漏洞。

这对我来说很有用,允许我在同一个文件中同时定位javascript和html的部分视图。帮助思维过程中看到html和相关部分在同一部分视图文件。


In View使用了分部视图,叫做_mypartialview。cshtml

<div>
    @Html.Partial("_MyPartialView",< model for partial view>,
            new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>

@section scripts{

    @Html.Partial("_MyPartialView",<model for partial view>, 
                  new ViewDataDictionary { { "Region", "ScriptSection" } })

 }

在局部视图文件

@model SomeType

@{
    var region = ViewData["Region"] as string;
}

@if (region == "HTMLSection")
{


}

@if (region == "ScriptSection")
{
        <script type="text/javascript">
    </script">
}

section不能在局部视图中工作,这是设计的。您可以使用一些自定义助手来实现类似的行为,但老实说,包含必要的脚本是视图的责任,而不是部分的责任。我建议使用主视图的@scripts部分来实现这一点,而不用担心脚本的部分。

普路托的想法比较好:

CustomWebViewPage.cs:

    public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {

    public IHtmlString PartialWithScripts(string partialViewName, object model) {
        return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html });
    }

    public void RenderScriptsInBasePage(HelperResult scripts) {
        var parentView = ViewBag.view as WebPageBase;
        var parentHtml = ViewBag.html as HtmlHelper;
        parentView.DefineSection("scripts", () => {
            parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString());
        });
    }
}

观点\ web . config:

<pages pageBaseType="Web.Helpers.CustomWebViewPage">

观点:

@PartialWithScripts("_BackendSearchForm")

部分(_BackendSearchForm.cshtml):

@{ RenderScriptsInBasePage(scripts()); }

@helper scripts() {
<script>
    //code will be rendered in a "scripts" section of the Layout page
</script>
}

布局页面:

@RenderSection("scripts", required: false)