User987
User987

Reputation: 3823

jQuery getJSON with .NET MVC not working

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???

Upvotes: 1

Views: 842

Answers (3)

Asif Raza
Asif Raza

Reputation: 1021

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

Upvotes: 1

Basanta Matia
Basanta Matia

Reputation: 1562

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.

Upvotes: 1

user7819643
user7819643

Reputation:

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

Upvotes: 1

Related Questions