在javascript中将c#数组转换为json

本文关键字:转换 json 数组 javascript 中将 | 更新日期: 2023-09-27 18:12:51

我正在将c#数组转换为javascript中的json在MVC视图上,如下所示

var selectedPatientGroups = JSON.parse('[@(Model.SelectedPatientDiscountGroups != null
                                                      ? string.Join(",", Model.SelectedPatientDiscountGroups)
                                                      : string.Empty)]')

如果模型。SelectedPatientDiscountGroups = string[]{"abc","cd"}那么我将得到json对象转换为

var selectedPatientGroups = [abc,cd]

但作为json对象,我期望为["abc","cd"]

我需要最好的解决方案。

在javascript中将c#数组转换为json

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

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

别白费力气了!使用JSON库,比如JSON。NET或内置的JavaScriptSerializer。它比引号要复杂得多。

但如果你坚持

JSON.parse('[@(Model.SelectedPatientDiscountGroups != null
               ? string.Join(",", Model.SelectedPatientDiscountGroups.Select(g => "'"" + g + "'"").ToArray()
               : string.Empty)]')