【问题标题】:Knockout mapping c# model to knockout model, parse C# code to json not workingKnockout 将 C# 模型映射到 Knockout 模型,将 C# 代码解析为 json 不起作用
【发布时间】:2018-01-21 16:59:40
【问题描述】:

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

【问题讨论】:

    标签: javascript c# json knockout.js asp.net-core


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 2012-04-14
      • 1970-01-01
      • 2013-05-17
      • 2012-12-05
      • 1970-01-01
      • 2013-03-21
      • 2014-07-31
      相关资源
      最近更新 更多