无法以json格式解析c#代码。
var model = ko.mapping.fromJS(ko.mapping.fromJSON('@Html.Raw(JsonConvert.SerializeObject(this.Model))'));
错误:
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响应:
{"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"}]}
如何将json字符串中的c#代码显示为字符串,而不是作为对象
我的模特:
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; }
}
}
ViewModelSnippet模型:
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; }
}
}
答案 0 :(得分:1)
我认为你的语法不正确。
您应该在控制器中序列化您的模型。
var jsonString = JsonConvert.SerializeObject(ViewModelSnippets);
return jsonString;
并相应地绑定。
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>