简体   繁体   中英

Converting C# array to json in javascript

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.

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)]')

为什么不使用内置的JSON序列化器?

var selectedPatientGroups = @Html.Raw(Json.Encode(Model.SelectedPatientDiscountGroups));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM