将 C# 模型挖空映射到挖空模型,将 C# 代码解析为 json 不起作用



不能以 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; }
}
}

我认为你的语法不正确。

应在控制器中序列化模型。

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>

最新更新