jQuery getJSON with .NET MVC not working

放肆的年华 提交于 2019-12-11 06:38:10

问题


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


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/43229760/jquery-getjson-with-net-mvc-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!