使用.NET MVC的jQuery getJSON不起作用

时间:2017-04-05 11:22:36

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-5

我在.NET MVC应用程序中加载页面时设置了一个getJSON调用,如下所示:

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

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

});

行动看起来像这样:

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

我收到了这个错误:

500 (Internal Server Error)

我在这里做错了什么???

3 个答案:

答案 0 :(得分:1)

在方法中更改返回类型并返回Json,如下面的

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

正如您在评论中提到的,您仍然会收到500错误。我认为这个控制器有 [Authorize] 属性,你在没有登录的情况下调用这个方法。在这种情况下,您可以使用GetAllUsers()中的 [AllowAnonymous] 属性来访问该方法。

答案 1 :(得分:1)

在MVC中,只有在出于某些安全目的向您发出post请求时才会返回json结果,除非您明确指定JsonRequestBehavior.AllowGet,否则也会更改您的返回类型

[HttpGet]
    [ActionName("GetAllUsers")]
    public JsonResult GetAllUsers()
    {
        return Json(ctx.zsp_select_allusers(), JsonRequestBehavior.AllowGet);
    }

答案 2 :(得分:1)

试试吧

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