Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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" });
     }
}
like image 476
Jean-Francois Avatar asked Mar 14 '11 15:03

Jean-Francois


People also ask

Can I use .NET with C?

. NET Framework is an object oriented programming framework meant to be used with languages that it provides bindings for. Since C is not an object oriented language it wouldn't make sense to use it with the framework.

Is ASP.NET a C?

Basically, ASP.NET is a web delivery mechanism that runs either C# or VB.NET in the background. C# is a programming language that runs ASP.NET as well as Winforms, WPF, and Silverlight.

How do I install ASP.NET on Windows 10?

In Control Panel, click Programs, and then click Turn Windows features on or off. In the Windows Features dialog box, click Internet Information Services to install the default features. Expand the Application Development Features node and click ASP.NET 4.5 to add the features that support ASP.NET.


2 Answers

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
};
like image 103
jbtule Avatar answered Oct 03 '22 04:10

jbtule


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.

like image 31
Ryan Avatar answered Oct 03 '22 04:10

Ryan