1

The c# code can not be parsed in json format.

var model = ko.mapping.fromJS(ko.mapping.fromJSON('@Html.Raw(JsonConvert.SerializeObject(this.Model))'));

Error:

VM444:1 Uncaught SyntaxError: Unexpected token 
 in JSON at position 375
    at JSON.parse (<anonymous>)
    at Object.kd (knockout.js:21)
    at Object.f.fromJSON (knockout-mapping.js:17)
    at (index):58

JSON Response:

{"Selection":"3e67e70f-af0e-41d8-ba6e-cb8c4f8487a2","CurrentSnippet":{"SnippetId":0,"Name":null,"Description":null,"Code":null,"Modified":"0001-01-01T00:00:00"},"Snippets":[{"SnippetId":11,"Name":"asd","Description":"sdasd","Code":null,"Modified":"8/13/17 9:59:10 PM"},{"SnippetId":12,"Name":"Standard","Description":"Standard Console Program","Code":"namespace TestProject {
    static class Program {
        static void Main(string[] args) {
            return 0;
        }
    }
}
","Modified":"8/13/17 10:04:17 PM"}]}

How can I display c# code in a json string as string, and not as object

My model:

using System;
using System.Collections.Generic;
using VoidProvider.Models.VoidModels;

    namespace VoidProvider.Models.SnippetViewModels
    {
        public class ViewModelSnippets
        {
            public Guid Selection { get; set; }
            public Snippet CurrentSnippet { get; set; }
            public List<ViewModelSnippet> Snippets { get; set; }
        }
    }

The ViewModelSnippet model:

using System;

namespace VoidProvider.Models.SnippetViewModels {
    public class ViewModelSnippet {
        public int SnippetId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Code {get; set;}
        public string Modified { get; set; }
    }
}

1 Answer 1

1

I don't think your syntax is correct.

You should serialize your model in your controller.

var jsonString = JsonConvert.SerializeObject(ViewModelSnippets);
return jsonString;

And bind accordingly.

var viewModel =  {
        Snippet: ko.observableArray()
    };

//Ajax Call
viewModel.Snippet= ko.mapping.fromJS(data);
ko.applyBindings(viewModel, document.getElementById("snippet"));

<div id="snippet">
<span data-bind="foreach: Snippets">
<span data-bind="text: code"></span>
</span>
</div>
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.