[英]Converting C# array to json in javascript
I am converting my C# array to json in javascript on MVC view as below 我正在将M#视图上的javascript中的C#数组转换为json,如下所示
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 如果Model.SelectedPatientDiscountGroups = string [] {“ abc”,“ cd”},那么我将转换后的json对象作为
var selectedPatientGroups = [abc,cd]
but as json object I am expecting as ["abc","cd"] 但是我希望作为json对象为[“ 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.
使用JSON库,例如Json.NET或内置的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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.