3

I want to use C# string array in JS plugin with razor syntax.

C# Code:(in cshtml)

@{ string[] extentions = new string[] { "jpg", "png", "gif", "jpeg", "pdf" }; } 

JS Code :

 $('#file').filer({ limit: 2, maxSize: 4000, extensions: ["jpg", "png", "gif", "jpeg", "pdf"], ... }) 

JS Code with C# string[]:

 $('#file').filer({ limit: 2, maxSize: 4000, extensions: '@extentions', ... }) 

In this case I get System.String[] and if I use JsonConvert.SerializeObject(extentions) I get something like this:

["jpg","png","gif","jpeg","pdf"] 

What is the best way convert c# string array to Js array in the format that I want?

2
  • 1
    Why not using plain javascript array (if the C# array is not coming from server)?CommentedMar 15, 2017 at 13:24
  • @amirmishori maybe server version is used somewhere else in the view at server side..
    – pwas
    CommentedMar 15, 2017 at 13:25

2 Answers 2

6

Use

@Html.Raw(JsonConvert.SerializeObject(extentions)) 

Html.Raw ensures that argument will not be html-encoded, so you won't get " instead of " anymore.

    0
    @{ <text>[</text> foreach (string extension in extensions) { <text>"@extension", </text> } <text>]</text> } 

    The code above will produce the output:

    ["jpg", "png", "gif", "jpeg", "pdf", ] 

    This is done by using the <text></text> tag which allows you to insert markup between the tags to be displayed within the View.

    At the start, a [ char is inserted. Then, it loops through each extension and outputs "extension",. After the loop is completed, it inserts a ] char to end the valid JavaScript array.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.