0

I want to push List of type string into value dictionary in js script. Js dictionary should contain key DateTime, and List as a value.

@foreach (KeyValuePair<DateTime, List<string>> item in Model.AssignedAttractions)
{
    <script type="text/javascript">
        var dictionary = [];

        $(function () {
            dictionary.push({
                key: @item.Key.ToShortDateString(),
                value: @item.Value.ToArray(),
            });
        });
    </script>
}

Presented solution value: @item.Value.ToArray()is not working.

11
  • try if this works @Html.Raw(Json.Serialize(item.Value)) Commented Sep 10, 2017 at 13:24
  • Should it work in Razor View? It shows me Json doesn't contain definition Serialize Commented Sep 10, 2017 at 13:26
  • add @using Newtonsoft.Json to the top of your view Commented Sep 10, 2017 at 13:27
  • No change after added import. Should Json be imported from System.Web.Helpers? Commented Sep 10, 2017 at 13:30
  • 1
    sorry try with @Html.Raw(JsonConvert.SerializeObject(item.Value)) Commented Sep 10, 2017 at 13:30

1 Answer 1

1

Add @using Newtonsoft.Json to your View. And then,

dictionary.push({
    key: @item.Key.ToShortDateString(),
    value: @Html.Raw(JsonConvert.SerializeObject(item.Value)),
});

JsonConvert.SerializeObject converts your C# object to a JSON string

You could also avoid the loop like this:

@Html.Raw(JsonConvert.SerializeObject(Model.AssignedAttractions.Select(a => new { key = a.Key.ToShortDateString(), value = a.Value })));
Sign up to request clarification or add additional context in comments.

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.