0

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.

2
  • possible duplicate of Json Serialization in C# Commented Jul 15, 2014 at 6:12
  • Is SelectedPatientDiscountGroups array of string? Commented Jul 15, 2014 at 6:12

2 Answers 2

1

Why not use the built-in JSON serializer?

var selectedPatientGroups = @Html.Raw(Json.Encode(Model.SelectedPatientDiscountGroups));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.