简体   繁体   English

如何在ajax成功方法中将javaScript json对象转换为C#对象

[英]How to Convert javaScript json object into C# object in ajax success method

I have this method on success of ajax call .我对 ajax 调用成功有这种方法。

var SuccessMethodToGetNavigation = function (response) {

    recieveTopLevelAndSecondLevel(response);

};

Response I get from API is an object of NavigationViewModel in success method in the form of json.我从 API 得到的响应是以 json 的形式在成功方法中的 NavigationViewModel 对象。 I want to cast this json object in C# NavigationViewModel class again to bind it with partial view model to get data in success method and then pass it to partialView model that is bound with NavigationViewModel and want to perform other operations.我想再次在 C# NavigationViewModel 类中强制转换这个 json 对象,将它与部分视图模型绑定以在成功方法中获取数据,然后将其传递给与 NavigationViewModel 绑定并想要执行其他操作的 partialView 模型。

Is it possible to do this without using another ajax call to controller ?是否可以在不使用另一个对控制器的 ajax 调用的情况下执行此操作?

A way to use JSON in C# is with JSON.NET Quick Starts & API Documentation from JSON.NET - Official site help you work with it.在 C# 中使用 JSON 的一种方法是使用来自 JSON.NET 的 JSON.NET 快速入门和 API文档- 官方网站帮助您使用它。 An example of how to use it:如何使用它的示例:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM