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

我该怎么做呢?


当前回答

你可以选择使用你的文件夹/索引。CSHTML作为母版,然后添加节脚本。然后,在你的布局中,你有:

@RenderSection("scripts", required: false) 

和index.cshtml:

@section scripts{
     @Scripts.Render("~/Scripts/file.js")
}

它会在所有的partialviews上工作。这对我很有用

其他回答

你可以使用这些扩展方法:(保存为PartialWithScript.cs)

namespace System.Web.Mvc.Html
{
    public static class PartialWithScript
    {
        public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
        {
            if (htmlHelper.ViewBag.ScriptPartials == null)
            {
                htmlHelper.ViewBag.ScriptPartials = new List<string>();
            }

            if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
            {
                htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
            }

            htmlHelper.ViewBag.ScriptPartialHtml = true;
            htmlHelper.RenderPartial(partialViewName);
        }

        public static void RenderPartialScripts(this HtmlHelper htmlHelper)
        {
            if (htmlHelper.ViewBag.ScriptPartials != null)
            {
                htmlHelper.ViewBag.ScriptPartialHtml = false;
                foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
                {
                    htmlHelper.RenderPartial(partial);
                }
            }
        }
    }
}

像这样使用:

示例partial:(_MyPartial.cshtml) 把html放在if里,js放在else里。

@if (ViewBag.ScriptPartialHtml ?? true)
    <p>I has htmls</p>
}
else {
    <script type="text/javascript">
        alert('I has javascripts');
    </script>
}

在你的_Layout中。cshtml,或者任何你想要渲染的部分脚本的地方,放置以下(一次):它将只在当前页面的这个位置渲染所有部分的javascript。

@{ Html.RenderPartialScripts(); }

然后使用您的部分,只需这样做:它将只呈现该位置的html。

@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}

我有一个类似的问题,我有一个母版页如下:

@section Scripts {
<script>
    $(document).ready(function () {
        ...
    });
</script>
}

...

@Html.Partial("_Charts", Model)

但是部分视图依赖于脚本部分中的一些JavaScript。我通过将部分视图编码为JSON来解决这个问题,将其加载到JavaScript变量中,然后使用它来填充一个div,因此:

@{
    var partial = Html.Raw(Json.Encode(new { html = Html.Partial("_Charts", Model).ToString() }));
}

@section Scripts {
<script>
    $(document).ready(function () {
        ...
        var partial = @partial;
        $('#partial').html(partial.html);
    });
</script>
}

<div id="partial"></div>

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

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

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

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

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

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

在页面中插入部分视图…

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

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

享受吧!

使用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()));
            }
        }
    }