Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

i have the following code in my _Layout.cshtml file. The idea is that in my javascript code some items about the security are filled in. LoggedIn and username are obviously no problem, but the way the roles are put in the javascript is wrong. The Roles is simply a string[] (that should become a JSON array.

But it shows as a '[& quot;user& quot;,& quot;'admin& quot;]' which obviously is not a valid JSON array. Any ideas how i can convert my string array to a valid JSON array? My code of the RolesArray is added below.

<script type="text/javascript">
    $(function () {
        require(['jquery','config', 'security'],
                function ($, config, security) {

                security.items.loggedIn = '@Request.IsAuthenticated';
                security.items.Username = '@User.Identity.Name';

                var one = '@((MyIdentity)User.Identity).RolesArray'
                $(document).trigger("security_changed");
           });
    });
</script>


public String[] RolesArray   
{
    get
    {
        var two = Roles.ToArray();
        return two;        
    }
}
share|improve this question

Use JSON.Net See the code below

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
share|improve this answer
1  
Thanks for the answer, but I did try to use JSON.NET to convert it in MyPrincipal class, but the rendering on the javascript on the client part remain faulty. Instead of ["user","'admin"] if got the middle quotes htmlencoded in my javascript "& quot;" – Patrick Sep 23 '13 at 11:08

It'd be nice if razor makes a native method for this.

In the meantime here is a simple (Without libraries) for-loop to accomplish it:

 @{
    <script>var array = []; </script> //create an empty js array

      for(int i = 0; i < Model.Count; i++)
      {
        <script> array[@i] = '@Model[i]'; </script> //pass each string to array
      }
 }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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