0

我在父视图中有 2 个 PartialView。

在这 2 个 PartiaView 中,我生成了一些 JavaScript 代码,这些代码需要包含在父视图的底部。

这是在 PartialViews 中生成一些 JavaScript 的 HtmlHelper 扩展。

public static MvcHtmlString KO_ObjectFor<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    String str = "some javascript code";
    return MvcHtmlString.Create(str);
}

这是父视图(主视图)

...
//First Partial View
<% Html.RenderPartial("_PartialViewFirst"); %>

//Second Partial View
<% Html.RenderPartial("_PartialViewSecond"); %>

//Here I need to display the JavaScript from the PartialViews
<script type="text/javascript">
   <%: Html.FunctionToConcatenateJavaScript() %>
</script>
...

什么是正确的方法?

4

2 回答 2

2

您可以使用 Stack 在 HttpContext 中推送和弹出脚本:

public static class HtmlExtensions
{
    private const string ScriptsKey = "__scripts__";

    public static MvcHtmlString KO_ObjectFor<TModel>(this HtmlHelper<TModel> htmlHelper)
    {
        var stack = htmlHelper.ViewContext.HttpContext.Items[ScriptsKey] as Stack<string>;
        if (stack == null)
        {
            stack = new Stack<string>();
            htmlHelper.ViewContext.HttpContext.Items[ScriptsKey] = stack;
        }
        String str = "some javascript code";
        stack.Push(str);

        return new HtmlString("some code that the helper needs to generate and output to the view");
    }

    public static IHtmlString FunctionToConcatenateJavaScript(this HtmlHelper htmlHelper)
    {
        var stack = htmlHelper.ViewContext.HttpContext.Items[ScriptsKey] as Stack<string>;
        if (stack == null)
        {
            return MvcHtmlString.Empty;
        }

        var scriptTag = new TagBuilder("script");
        scriptTag.Attributes["type"] = "text/javascript";
        var sb = new StringBuilder();
        foreach (var script in stack)
        {
            sb.AppendLine(script);
        }
        scriptTag.InnerHtml = sb.ToString();

        return new HtmlString(scriptTag.ToString());
    }
}

然后你可以推:

<%= Html.KO_ObjectFor(x => x.Foo) %>
<%= Html.KO_ObjectFor(x => x.Bar) %>
...

然后将它们全部弹出主人:

<%= Html.FunctionToConcatenateJavaScript() %>
于 2012-05-25T12:48:55.140 回答
0

也许你可以这样做:

第 1 部分:

@{
    ViewBag.JS = @Html.KO_ObjectFor(firstJs);
}

第 2 部分:

@{
    ViewBag.JS += @Html.KO_ObjectFor(secondJs);
}

主要的:

<script type="text/javascript">
   @ViewBag.JS
</script>

抱歉,剃刀语法

于 2012-05-25T12:42:58.853 回答