【问题标题】:jQuery getJSON with .NET MVC not working带有.NET MVC的jQuery getJSON不起作用
【发布时间】:2017-08-30 23:36:24
【问题描述】:

当页面加载到我的 .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)

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

【问题讨论】:

  • return Json(ctx.zsp_select_allusers(), JsonRequestBehavior.AllowGet);
  • 去掉 Administrator/GetAllUsers 前的斜杠 / 并检查。你的返回类型应该是 JsonReturn
  • 并且它需要是public ActionResult GetAllUsers()public JsonResult GetAllUsers()
  • @BasantaMatia 仍然无法正常工作:/
  • 不需要.ToList()(它正在序列化,因此正在迭代集合)

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


【解决方案1】:

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

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

【讨论】:

  • 这很愚蠢,但尝试删除[HttpGet][ActionName("GetAllUsers")]
  • 如果仍然出现错误,请编辑您的问题并粘贴控制器的代码。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    试试看

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2013-05-17
      • 2017-09-05
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多