c# - How to write quotes (" or ') and quoted strings to a Razor view -


i have bunch of constants used in js saved in 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 simple class write js on 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 view, i'm doing this:

@section scripts {     <script>         @javascriptresourcerenderer.renderpageconstants()     </script> } 

the constants rendered when view loads, except quotes come out encoded.

viewing html using dom inspector, see:

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

i've tried

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

how can write

<script>     var month_picker_format = "yyyy-mm"; // or 'yyyy-mm' (i want quotes!) </script> 

to view?

you should return output mvchtmlstring instead, otherwise mvc 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, can use html helper method html.raw in view, need remember every time call method (which why not recommend way):

@html.raw(javascriptresourcerenderer.renderpageconstants()) 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -