2

I have an error in this code. I deserialize a JSON file and stored that data in the database now I want to show that data from my database.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;

using ReadingFromDb.Dto;

namespace ReadingFromDb.Controller
{
    public class StudentController
    {
        [HttpGet]
        [AllowAnonymous]
        public async Task<JsonResult> GetStudents()
        {
            using (var context = new UNIEntities1())
            {
                var query = @"Select ";
                var dbQuery = context.Database.SqlQuery<StudentDto>(query);
                var list = await dbQuery.ToListAsync();
                return Json(list,JsonRequestBehavior.AllowGet);
            }
        }
    }
}

Error is:

JSON can not be used like method.

What should I do?

2
  • This looks like code from an ASP.NET MVC project - is that correct? Commented Dec 5, 2019 at 6:46
  • Did you store the data in json format? If yes then why are you returning it as return Json() again. Commented Dec 5, 2019 at 6:50

3 Answers 3

2

Your contoller must be extend the base class Controller in which the Json() virtual method is available:

public class StudentController : Controller
{
  // your code
}
Sign up to request clarification or add additional context in comments.

Comments

1

To resolve this error you can try as below

    public class StudentController : Controller
    {
      // your code
     }


    [HttpGet]
    [AllowAnonymous]
    public async Task<JsonResult> GetStudents()
    {
        using (var context = new UNIEntities1())
        {
            var list = await context.StudentDto.ToListAsync();
            return Json(list,JsonRequestBehavior.AllowGet);
        }
    }

Comments

1

What you need to do is to extend your StudentCotroller with Controller then put your code under that.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;

using ReadingFromDb.Dto;

namespace ReadingFromDb.Controller
{
    public class StudentController:Controller
    {
        [HttpGet]
        [AllowAnonymous]
        public async Task<JsonResult> GetStudents()
        {
            using (var context = new UNIEntities1())
            {
                var query = @"Select ";
                var dbQuery = context.Database.SqlQuery<StudentDto>(query);
                var list = await dbQuery.ToListAsync();
                return Json(list,JsonRequestBehavior.AllowGet);
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.