简体   繁体   English

如何在C#中访问返回的json中的数据?

[英]How can I access the data in the returned json in c#?

I have a method abc() returning: 我有一个方法abc()返回:

return Json(new { success = false, responseText = "Input-Values not valid" }, JsonRequestBehavior.AllowGet);

I use this method in an ajax-call (in javascript) as well as in another method in the same class (in c#). 我在ajax调用(在javascript中)以及同一类的另一种方法(在c#中)中使用了此方法。 In the ajax-call, I can check if success=true. 在ajax调用中,我可以检查成功是否为true。

How can I do that in c#? 我该如何在C#中做到这一点? Do I have to parse it there? 我必须在那里解析吗?

What I want to do is sth like: 我想做的是:

public ActionResult xyz(string x, string y) { 
   ActionResult result= this.abc();
   //if result.success==false than get responseText and do something
}

Have 2 functions 有2个功能

private MyObject abc()
{
    //your going to have to create a MyObject class
    return new MyObject(){ success = false, responseText = "Input-Values not valid" };
}

public ActionResult ABC()
{
    return Json(this.abc());
}

Then its just: 然后它只是:

public ActionResult xyz(string x, string y) { 
   MyObject result= this.abc();
   if (result.success){

  }
}

It'd be good practice to move private MyObject abc() into a new logic class. 最好将private MyObject abc()移到新的逻辑类中。 This will help keep your controller "skinny". 这将有助于使您的控制器保持“瘦”状态。

You don't seem to understand methods in C# very well. 您似乎不太了解C#中的方法。 I'd suggets you do some more reading up on the subject, eg https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods 我建议您进一步阅读该主题,例如https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/methods

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

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