Harsh
Harsh

Reputation: 33

How to return Json data from MVC Controller in C#

I am using a Repository pattern with Entity Framework, When i run my code instead of Json Data I am getting -> System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]

Repository

public interface IRepository<T> where T : class
{
    IEnumerable<T> Get();

    T GetDetails(Guid Id);

    void Insert(T data);

    void Delete(T data);

    void Update(T data);

    void Save();
}

public GenericRepository()
        {
            context = new Entities();
            dbEntity = context.Set<T>();
        }

Services

public class TestService : ITestService
    {
        public TestService(
           IRepository<User> userRepository
           )
        {
            _userRepository = userRepository;
        }

        private readonly IRepository<User> _userRepository;

        public IEnumerable<User> Get()
        {

            var result = _userRepository.Get();

            return result;
        }
    }

Controller

public class HomeController : Controller
{
    public HomeController(ITestService testService)
    {
        _testService = testService;
    }

    private readonly ITestService _testService;

    public IEnumerable<User> Index()
    {
        var result = _testService.Get();

        return result;
    }
}

I found some solution on here (StackOverflow) that I need to add WebApiConfig, I added as below but it also not work. I am getting the output System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]

 public static class WebAppConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Remove(new XmlMediaTypeFormatter());

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

        config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new
            {
                id = RouteParameter.Optional
            }
        );
    }
}

Here is my Git Repository Link https://github.com/Harshk16/MovieInfo

Please help me out how to get output in Json Format

Upvotes: 2

Views: 14197

Answers (2)

Shyju
Shyju

Reputation: 218842

If you want to return JSON response form your MVC controller action method, you may use the Json method.

The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.

The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)

public JsonResult Index()
{
    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);
}

Or

public ActionResult Index()
{
    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);
}

Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebAppConfig.Register);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Your other existing code
}

and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial

public class UsersController : ApiController
{
    public IEnumerable<User> Get()
    {
        var result = new List<User>
        {
            new User { Id = Guid.NewGuid() , DisplayName = "Shyju"},
            new User { Id = Guid.NewGuid(), DisplayName = "Scott"}
        };
        // Hard coded list of users. 
        // Once you fix your DI setup, you can use your service to get data.
        return result;
    }
}

By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL

http://yourSiteBaseUrl/api/users/get

If you do not want the get in your API Urls, simply fix your route template when registering the web api routing

routeTemplate: "api/{controller}/{id}"

Upvotes: 2

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16846

To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.

When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.

public class HomeController : ApiController
{
    public HomeController(ITestService testService)
    {
        _testService = testService;
    }

    private readonly ITestService _testService;

    public IEnumerable<User> Index()
    {
        var result = _testService.Get();

        return result;
    }
}

Upvotes: 1

Related Questions