2017-04-05 46 views
1

我已經建立了的getJSON呼叫時在我的.NET MVC應用程序頁面加載這樣的:的jQuery的getJSON與.NET MVC不工作

$(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) 

我在做什麼錯在這裏???

+2

'return Json(ctx.zsp_select_allusers(),JsonRequestBehavior.AllowGet);' –

+1

在Administrator/GetAllUsers之前刪除斜線並檢查。你的返回類型應該是JsonReturn –

+1

它的需要是public ActionResult GetAllUsers()或public JsonResult GetAllUsers() –

回答

1

更改返回類型的方法並返回JSON,像波紋管,

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

正如您在您的評論中提到,你仍然得到500錯誤。我認爲這個控制器有[授權]屬性,你不用登錄就調用這個方法。在這種情況下,您可以在GetAllUsers()中使用[AllowAnonymous]屬性來訪問該方法。

1

在MVC中,如果您post要求它的一些安全起見,直到除非你明確指定JsonRequestBehavior.AllowGet,也改變你的返回類型

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

獲取內部服務器錯誤仍然... – User987

+2

這很愚蠢,但嘗試刪除'[HttpGet]'和'[ActionName(「GetAllUsers」)]' – 2017-04-05 11:49:36

+0

如果仍然出現錯誤,請編輯您的問題並粘貼控制器的代碼。 – 2017-04-05 12:19:26

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); 
    } 
JSON結果纔會返回