2017-08-13 38 views
1

C#代码无法在JSON格式中解析。敲除映射C#模型敲除模型,解析C#代码到JSON不起作用

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; } 
    } 
} 

回答

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> 
+0

谢谢!!!!! –