开发者

Making an Ajax request to a page method in ASP.NET MVC 2

开发者 https://www.devze.com 2022-12-28 09:12 出处:网络
I\'m trying to call a page method belonging to a MVC Controller from another site, by means of: $.ajax({

I'm trying to call a page method belonging to a MVC Controller from another site, by means of:

$.ajax({
          type: "GET",
          url: "http://localhost:54953/Home/ola",
          data: "",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(data) {
                console.log(data.Name);
          }
        });

the method code is as follows, really simple, just to test:

 public ActionResult ola()
    {

        return Json(new ActionInfo()
        {
            Name = "ola"
        },JsonRequestBehavior.AllowGet);

    }

I've seen this aproach being suggested here, and I actually like it a lot, should it work...

When I run this, firebug gets a 200 OK, but the data received is null.

I've tried a lot of different approaches, like having the data in text (wish grants me "(an empty string)" instead开发者_高级运维 of just "null") or returning string in the server method...

Can you tell me what am I doing wrong?

Thank you in advance,

João


Have you tried returning your JSON like so...

public ActionResult ola()
{
    return Json(new { Name = "ola" }, JsonRequestBehavior.AllowGet);
}


Controller:

public ActionResult Ola()
{
    // No need to use a custom ActionInfo type here, an anonymous type
    // will be just fine:
    return Json(new { Name = "ola" }, JsonRequestBehavior.AllowGet);
}

View:

$(function {
    $.getJSON('/home/ola', function(json) {
        alert(json.Name);
    });
});


You could try returning JsonResult from the controller action method. Method signature would then be public JsonResult ola(). Hope it helps.


Thanks for all the feedback. I found out that everything I was doing was right and wrong at the same time.

the requests were all functional, but the request was being made to a different domain, wich is automatically blocked by the browsers (except IE). It's a question of security. But since the request was meant to work on a mobile device, when i tested it there, it worked perfectly.

Once again, thanks to everyone who answered, i'll adopt some of the ideas shown here :)


if you are making an ajax call cross domain. Have you tried setting your data type to

dataType: jsonp

jquery ajax cross domain

0

精彩评论

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