2

我编写了一个自定义 HTMLHelper 来输出一些 javascript。javascript 正在添加到页面中,但在页面加载时并未运行。如果我将生成的 JS 复制/粘贴到 Chrome 的控制台窗口中,则该脚本可以完美运行。我想做的事可能吗?

public static HtmlString CreatePieChart(this HtmlHelper helper, string divId, int width, Collection<PieChartSeriesItem> series)
    {            
        if (width < 1)
        {
            throw new System.ArgumentException("Width of pie chart must be greater than zero");
        }

        StringBuilder htmlString = new StringBuilder();
        htmlString.Append("<script type=\"type/javascript\">");
        htmlString.Append("$(window).load(\"#");
        htmlString.Append(divId);
        htmlString.Append("\").kendoChart({");
        htmlString.Append("title: { visible: false },");
        htmlString.Append("chartArea: { background: \"transparent\", width: ");
        htmlString.Append(width.ToString(CultureInfo.InvariantCulture));
        htmlString.Append(" },");
        htmlString.Append("legend: { visible: false },");
        htmlString.Append("seriesDefaults: { labels: { visible: false } },");
        htmlString.Append("series: [{");
        htmlString.Append("type: \"pie\",");
        htmlString.Append("padding: 0,");
        htmlString.Append("overlay: { gradient: \"none\"},");
        htmlString.Append("data: [");

        htmlString.Append(CreatePieChartDataSeriesString(series));

        htmlString.Append("]");
        htmlString.Append("}],");
        htmlString.Append("tooltip: { visible: true, template: \"#= category # (#= value #%)\"}");
        htmlString.Append("});");
        htmlString.Append("</script>");

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

这是页面中的调用

<div id="piechart">
    @Html.Partial("_PieChart", Model.BalancePieChartData)
</div>
4

1 回答 1

4

我已经尝试过了,它工作正常。

public static MvcHtmlString Test(this HtmlHelper htmlHelper)
    {
        StringBuilder htmlString = new StringBuilder();
        htmlString.Append("<script type=\"text/javascript\">");
        htmlString.Append("alert(1)");
        htmlString.Append("</script>");
        return new MvcHtmlString(htmlString.ToString());
    }

我把它放在我的身体上,就像这样:

@Html.Test()

我的浏览器工作正常警报 1。

所以我想也许你只是把这行写错了

htmlString.Append("<script type=\"type/javascript\">");

它应该是“文本/javascript”

于 2013-05-08T03:20:28.967 回答