1

I have setup a getJSON call when page loads in my .NET MVC app like this:

$(document).ready(function(){
   $.getJSON("/Administrator/GetAllUsers", function (res) {

            // getting internal server error here...
        });

});

And the action looks like this:

  [HttpGet]
    [ActionName("GetAllUsers")]
    public string GetAllUsers()
    {
        return new JavaScriptSerializer().Serialize(ctx.zsp_select_allusers().ToList());
    }

I'm getting this error:

500 (Internal Server Error)

What am I doing wrong here???

12
  • 2
    return Json(ctx.zsp_select_allusers(), JsonRequestBehavior.AllowGet); Commented Apr 5, 2017 at 11:25
  • 1
    Remove the slash / before Administrator/GetAllUsers and check. Your return type should be JsonReturn Commented Apr 5, 2017 at 11:26
  • 1
    And its needs to be public ActionResult GetAllUsers() or public JsonResult GetAllUsers() Commented Apr 5, 2017 at 11:27
  • @BasantaMatia still not working :/ Commented Apr 5, 2017 at 11:27
  • 1
    There is no need for .ToList() (its being serialized, so therefore the collection is being iterated) Commented Apr 5, 2017 at 11:30

3 Answers 3

1

In MVC, json result only returned if you make post request to it for some security purposes, until and unless you explicitly specify JsonRequestBehavior.AllowGet, also change your return type

[HttpGet]
    [ActionName("GetAllUsers")]
    public JsonResult GetAllUsers()
    {
        return Json(ctx.zsp_select_allusers(), JsonRequestBehavior.AllowGet);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

It's silly but try to remove [HttpGet] and [ActionName("GetAllUsers")]
If still you get the error, edit your question and paste code of your controller.
1

Change your return type in method and return Json, like bellow,

[HttpGet]
[ActionName("GetAllUsers")]
public ActionResult GetAllUsers()
{
    var data = ctx.zsp_select_allusers().ToList();
    return Json(data, JsonRequestBehavior.AllowGet);
}

As you have mentioned in your comment, you are still getting 500 error. I think this controller have [Authorize] attribute and you are calling this method without login. In this case you can use [AllowAnonymous] attribute in GetAllUsers() to access the method.

Comments

1

try it

$.getJSON('@Url.Action("GetAllUsers", "Administrator")', function (res)   {

            alert(res);
        });

 [HttpGet]
    public ActionResult GetAllUsers( ) {

          //get the data from db , then send it
          //i'm passing dummy text 'got it'

        return Json("got it", 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.