如何在Razor视图

时间:2015-07-23 10:42:12

标签: c# razor asp.net-mvc-5

我在RESX文件中保存的JS中使用了一堆常量,例如:

DATE_PICKER_FORMAT   yyyy-mm-dd  
DATETIME_FORMAT      yyyy-mm-dd hh:mm:ss  
MONTH_PICKER_FORMAT  yyyy-mm  

我写了一个简单的类来帮助在Razor视图中将其写入JS:

public static class JavascriptResourceRenderer
{
    private static string Render(ResourceSet resources)
    {
        string resourceString = "";

        foreach (DictionaryEntry resource in resources)
        {
            resourceString += String.Format("var {0} = '{1}'; ", resource.Key, resource.Value);
        }

        return resourceString;
    }

    public static string RenderPageConstants()
    {
        ResourceSet resources = PageConstants.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        return Render(resources);
    }
}

在我看来,我这样做:

@section Scripts
{
    <script>
        @JavascriptResourceRenderer.RenderPageConstants()
    </script>
}

当视图加载时,常量会被渲染,除了引号出来编码。

使用DOM检查器查看HTML,这就是我所看到的:

<script>
    var MONTH_PICKER_FORMAT = &#39;yyyy-mm&#39;;  
</script>

我试过

"var {0} = '{1}'; "   // writes &#39;yyyy-mm&#39; to view
"var {0} = \"{1}\"; " // writes &quot;yyyy-mm&quot; to view
@"var {0} = "{1}"; "  // syntax error in String.Format 

我该怎么写

<script>
    var MONTH_PICKER_FORMAT = "yyyy-mm"; // or 'yyyy-mm' (I want the quotes!)
</script>

到视图?

2 个答案:

答案 0 :(得分:5)

您应该将输出作为MvcHtmlString返回,否则MVC将对其进行编码:

private static MvcHtmlString Render(ResourceSet resources)
{
    string resourceString = "";

    foreach (DictionaryEntry resource in resources)
    {
        resourceString += String.Format("var {0} = '{1}'; ", resource.Key, resource.Value);
    }

    return new MvcHtmlString(resourceString);
}

或者,您可以在视图中使用Html Helper方法Html.Raw,但是您需要记住在调用方法的每个时间执行该操作(这就是我不建议的原因)这样做):

@Html.Raw(JavascriptResourceRenderer.RenderPageConstants())

答案 1 :(得分:4)

您的字符串正在进行HTML编码。

您需要输出原始文字。您的观点需要这样做:

@section Scripts
{
    <script>
        @Html.Raw(JavascriptResourceRenderer.RenderPageConstants())
    </script>
}