I have a bunch of constants to be used in JS saved in a RESX file, such as:
DATE_PICKER_FORMAT yyyy-mm-dd
DATETIME_FORMAT yyyy-mm-dd hh:mm:ss
MONTH_PICKER_FORMAT yyyy-mm
I wrote a simple class to help write this into JS on a Razor view:
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);
}
}
And in my view, I'm doing this:
@section Scripts
{
<script>
@JavascriptResourceRenderer.RenderPageConstants()
</script>
}
The constants do get rendered when the view loads, except the quotes come out encoded.
Viewing the HTML using DOM inspector, this is what I see:
<script>
var MONTH_PICKER_FORMAT = 'yyyy-mm';
</script>
I've tried
"var {0} = '{1}'; " // writes 'yyyy-mm' to view
"var {0} = \"{1}\"; " // writes "yyyy-mm" to view
@"var {0} = "{1}"; " // syntax error in String.Format
How can I write
<script>
var MONTH_PICKER_FORMAT = "yyyy-mm"; // or 'yyyy-mm' (I want the quotes!)
</script>
to the view?
Use single quotes inside double quotes (and vice versa). Escape the quotes inside a string with a backslash.
Single and Double Quote in Character or Literal To have a double quote as a character in a string literal, do something like, char ident[] = "ab"cd"; The backslash is used in an escape sequence, to avoid conflict with delimiters. To have a double quote as a character, there is no need for the backslash: '”' is alright.
The HTML <q> tag defines a short quotation. Browsers normally insert quotation marks around the quotation.
You should return your output as an MvcHtmlString
instead, otherwise MVC will encode it:
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);
}
Alternatively, you can use the Html Helper method Html.Raw
in your view, but you need to remember to do that every time you call the method (which is why I would not recommend to do it this way):
@Html.Raw(JavascriptResourceRenderer.RenderPageConstants())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With