Reputation: 833
I am converting my C# array to json in javascript on MVC view as below
var selectedPatientGroups = JSON.parse('[@(Model.SelectedPatientDiscountGroups != null
? string.Join(",", Model.SelectedPatientDiscountGroups)
: string.Empty)]')
if Model.SelectedPatientDiscountGroups = string[]{ "abc","cd" } then I will get converted json object as
var selectedPatientGroups = [abc,cd]
but as json object I am expecting as ["abc","cd"]
I need best solution for this.
Upvotes: 0
Views: 132
Reputation: 1737
Don't reinvent the wheel! Use a JSON library such as Json.NET or the built-in JavaScriptSerializer. It is much more complicated than just quotes.
But if you insist
JSON.parse('[@(Model.SelectedPatientDiscountGroups != null
? string.Join(",", Model.SelectedPatientDiscountGroups.Select(g => "\"" + g + "\"").ToArray()
: string.Empty)]')
Upvotes: 1
Reputation: 49095
Why not use the built-in JSON serializer?
var selectedPatientGroups = @Html.Raw(Json.Encode(Model.SelectedPatientDiscountGroups));
Upvotes: 1