2011-07-07 70 views
0

現在我正在學習MVC的Ajax實現,並且無法正常工作。下面是我有:Ajax.ActionLink失敗

@Ajax.ActionLink("Click here to get a title", "Yo", 
    new AjaxOptions { OnSuccess = "alert(\"YES!\")", OnFailure = "alert(\"WHY?!\")" }) 

這裏是兩個控制器方法:

public PartialViewResult GetThatTitle() 
    { 
     var titular = new TitleDataEntity { }; 
     titular.TitleName = "Inception!"; 
     titular.PublishDate = DateTime.Now; 
     titular.Id = 2; 

     return PartialView("_testView", titular); 
    } 

    public JsonResult Yo() 
    { 
     var titular = new TitleDataEntity { }; 
     titular.TitleName = "Inception!"; 
     titular.PublishDate = DateTime.Now; 
     titular.Id = 2; 
     if(Request.IsAjaxRequest()) 
     { 
      return Json(titular); 
     } 
     return Json(titular); 
    } 

當我調用該函數「喲」,瀏覽器給我「WHY?」警報框。但是當我打電話給GetThatTitle時,它給了我成功的警報。爲什麼當我嘗試並返回Json結果時失敗?

回答

0

你需要讓這樣的GET請求時返回JSON在默認情況下禁用:

return Json(titular, JsonRequestBehavior.AllowGet); 

而且我會強烈建議您使用FireBug。它在控制檯中顯示所有AJAX請求,並且您可以看到請求和響應。如果你使用它,你會看到如下:

出現InvalidOperationException:此 請求已被阻止,因爲 敏感信息可以 透露給第三方網站 當此GET請求中被使用。爲了 允許GET請求,設置 JsonRequestBehavior到AllowGet]

將投入你當然在正確的軌道上。

+0

男人,我覺得自己像一個白癡。感謝您的幫助和及時的回覆。你搖滾。 – user558594