4

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?

  • 1
    Why not using plain javascript array (if the C# array is not coming from server)? – amir mishori Mar 15 '17 at 13:24
  • @amirmishori maybe server version is used somewhere else in the view at server side.. – pwas Mar 15 '17 at 13:25
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.