7

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; } } 

    2 Answers 2

    13

    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); 
    1
    • 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
      CommentedSep 23, 2013 at 11:08
    0

    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 } } 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.