我在我的_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视图中注入一些内容。

我该怎么做呢?


当前回答

使用Mvc Core,你可以创建一个整洁的TagHelper脚本,如下所示。这可以很容易地转换成一个节标记,在这里您也可以给它一个名称(或者名称取自派生类型)。注意,需要为IHttpContextAccessor设置依赖注入。

当添加脚本时(例如在部分中)

<scripts>
    <script type="text/javascript">
        //anything here
    </script>
</scripts>

当输出脚本时(例如在一个布局文件中)

<scripts render="true"></scripts>

Code

public class ScriptsTagHelper : TagHelper
    {
        private static readonly object ITEMSKEY = new Object();

        private IDictionary<object, object> _items => _httpContextAccessor?.HttpContext?.Items;

        private IHttpContextAccessor _httpContextAccessor;

        public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var attribute = (TagHelperAttribute)null;
            context.AllAttributes.TryGetAttribute("render",out attribute);

            var render = false;

            if(attribute != null)
            {
                render = Convert.ToBoolean(attribute.Value.ToString());
            }

            if (render)
            {
                if (_items.ContainsKey(ITEMSKEY))
                {
                    var scripts = _items[ITEMSKEY] as List<HtmlString>;

                    var content = String.Concat(scripts);

                    output.Content.SetHtmlContent(content);
                }
            }
            else
            {
                List<HtmlString> list = null;

                if (!_items.ContainsKey(ITEMSKEY))
                {
                    list = new List<HtmlString>();
                    _items[ITEMSKEY] = list;
                }

                list = _items[ITEMSKEY] as List<HtmlString>;

                var content = await output.GetChildContentAsync();

                list.Add(new HtmlString(content.GetContent()));
            }
        }
    }

其他回答

我能想到的第一个解决方案是使用ViewBag来存储必须呈现的值。

我从来没有试过,如果这个工作从一个局部的观点,但它应该在我看来。

我们看待网络的方式有一个根本性的缺陷,尤其是在使用MVC的时候。缺陷在于JavaScript在某种程度上是视图的责任。视图是视图,JavaScript(行为或其他)是JavaScript。在Silverlight和WPF的MVVM模式中,我们面临着“视图优先”或“模型优先”的问题。在MVC中,我们应该总是尝试从模型的角度进行推理,而JavaScript在很多方面都是这个模型的一部分。

我建议使用AMD模式(我自己喜欢RequireJS)。在模块中分离你的JavaScript,定义你的功能,从JavaScript中钩子到你的html,而不是依赖于一个视图来加载JavaScript。这将清理您的代码,分离您的关注点,并使生活变得更简单。

有一种方法可以在局部视图中插入部分,尽管它并不漂亮。你需要从父视图中访问两个变量。由于部分视图的部分目的就是创建该section,因此需要这些变量是有意义的。

下面是在局部视图中插入一个section的样子:

@model KeyValuePair<WebPageBase, HtmlHelper>
@{
    Model.Key.DefineSection("SectionNameGoesHere", () =>
    {
        Model.Value.ViewContext.Writer.Write("Test");
    });
}

在页面中插入部分视图…

@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))

您还可以使用此技术在任何类中以编程方式定义节的内容。

享受吧!

我刚刚在我的部分视图上添加了这段代码,解决了这个问题,虽然不是很干净,但它是有效的。你必须确保你渲染的对象的id。

<script>
    $(document).ready(function () {
        $("#Profile_ProfileID").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#TitleID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#CityID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#GenderID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
        $("#PackageID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
    });
</script>

普路托的想法比较好:

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)