开发者

Ajax.ActionLink failing

Right now I'm learning about MVC's implementation of Ajax and I'm having trouble getting it to work correctly. Here's what I have:

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

And here ar开发者_Go百科e the two controller methods:

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

When I call the function "Yo", the browser gives me the "WHY?!" alert box. But when I call GetThatTitle, it gives me the success alert. Why is it failing when I try and return a Json result?


You need to allow GET requests like this when returning JSON which are disabled by default:

return Json(titular, JsonRequestBehavior.AllowGet);

Also I would strongly recommend you using FireBug. It shows all AJAX requests in its console and you see the requests and responses. If you have used it you would have seen the following:

InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.]

which would have put you on the right track of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜