ASP.NET从服务器获取JSON对象

时间:2014-07-03 22:54:29

标签: jquery asp.net-mvc json

我试图通过ajax调用来获取JSON对象,但我无法。我不明白我在做错了什么。这是我的控制器:

public class RandomController : Controller
{
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// Returns a JSON representation of a Content corresponding to the content ID passed in.
        /// </summary>
        /// <returns></returns>
        public JsonResult GetStuff()
        {
            string x = "testing";
            return Json(x, JsonRequestBehavior.AllowGet);
        }
    }

这是我的ajax请求:

 $(document).ready(function () {
        $('#randombtn').click(function () {
            $.ajax({
                url: '/Random/GetStuff/',
                success: function (data) {
                    alert(data);
                }
            });
        });
    });

和我的按钮:

<input id="randombtn" type="button" value="Testing" />

单击按钮时没有任何反应。

2 个答案:

答案 0 :(得分:1)

$('#randombtn').click(function () {
    $.getJSON("/Random/GetStuff",function(data){
      alert(data);
    });
});

试试上面的

答案 1 :(得分:1)

你必须使用@Url.Action()帮助器以这种方式放置url,以便从控制器和操作名称生成正确的URL到genrate right url:

$('#randombtn').click(function () {
            $.ajax({
                url: '@Url.Action("GetStuff","Random")',
                success: function (data) {
                    alert(data);
                }
            });

当您输入 / Random / GetStuff 时,它将始终查看此URL以获取操作名称。但是使用@Url.Action()会生成正确的网址,无论你需要网址,都可以使用它来获取正确的网址。

请参阅MSDN Docs for Details