如何让我的Asp.Net C#类返回一个JSON格式 [英] How can My Asp.Net C# class return a json format

查看:104
本文介绍了如何让我的Asp.Net C#类返回一个JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何想一类,将返回一个JSON格式。

这个方法工作的高度控制器
但是当我想要把一个类,JSON对象似乎并不存在。

 公共JsonResult测试()
 {
      //错误1'的Json'这个名字并不在目前的情况下存在C:\\的Inetpub \\ wwwroot的\\ mvcinfosite \\ mvcinfosite \\确认\\ ValidationClass \\ BaseValidator.cs 66 20 mvcinfosite
      返回JSON(新{ERRMSG =测试});
 }

我想把那个code在一个简单的类。我希望能够调用这个方法在许多控制器。

感谢。

修改

这是我班的(如code这么想的工作)

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用mvcinfosite.Models;
使用mvcinfosite.Base;
使用System.Web.Mvc;公共类BaseValidator
{
     公共JsonResult测试()
     {
         返回JSON(新{ERRMSG =测试});
     }
}


解决方案

JSON()是主控制器,它返回一个JsonResult上的方法。你需要自己做的序列化。

 返回新的JavaScriptSerializer()序列化(新{ERRMSG =测试});

您将需要包括使用System.Web.Script.Serialization

How would like a class that will return a json format.

This method work Great in the controller but when I want to put in a Class, the Json object don't seem to exist.

 public JsonResult Test()
 {
      //Error   1   The name 'Json' does not exist in the current context   C:\inetpub\wwwroot\mvcinfosite\mvcinfosite\Validation\ValidationClass\BaseValidator.cs  66  20  mvcinfosite
      return Json(new { errMsg = "test" });
 }

I want to put that code in a simple class. I want be able to call this method in many controllers.

Thanks.

EDIT
This is my Class (Where the code dosen't work)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using mvcinfosite.Models;
using mvcinfosite.Base;
using System.Web.Mvc;

public class BaseValidator
{
     public JsonResult Test()
     {
         return Json(new { errMsg = "test" });
     }
}

解决方案

Json() is a method on the base controller which returns a JsonResult. You need to do the serialization yourself.

return new JavaScriptSerializer().Serialize(new { errMsg = "test" });

You will need to include using System.Web.Script.Serialization.

这篇关于如何让我的Asp.Net C#类返回一个JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆