我在父 View 中有 2 个 PartialView。
在这 2 个 PartiaView 中,我生成了一些 JavaScript 代码,需要将其包含在父 View 的底部。
这是 HtmlHelper 扩展,它在 PartialViews 中生成一些 JavaScript。
public static MvcHtmlString KO_ObjectFor<TModel>(this HtmlHelper<TModel> htmlHelper)
{
String str = "some javascript code";
return MvcHtmlString.Create(str);
}
这是父View(主View)
...
//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>
...
正确的方法是什么?
最佳答案
您可以使用堆栈在 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() %>
关于c# - 如何在 PartialViews 内连接使用 HtmlHelper 扩展生成的 JavaScript 并添加到父 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10754138/