How can My Asp.Net C# class return a json format

爱⌒轻易说出口 提交于 2019-11-27 04:37:32

问题


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

回答1:


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.




回答2:


return Json(new { errMsg = "test"});

is a convenience method on Controller that is equivalent to

return new JsonResult(){
      Data = new { errMsg = "test"},
      JsonRequestBehavior = JsonRequestBehavior.DenyGet
};



回答3:


For me this worked (mind the change of the return type to Object):

public Object Test()
{
      return new { errMsg = "test" };
}


来源:https://stackoverflow.com/questions/5300855/how-can-my-asp-net-c-sharp-class-return-a-json-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!