我在我的ASP.NET MVC应用程序中的“控制器”文件夹中有一个HomeController。我的视图位于:“View/Home/Index.cshtml”(请看下图)。C#MVC使用AJAX调用不同路径的方法
我使用Ajax来每隔几秒就得到一些json文件。问题出在Ajax URL中,因为我真的不知道,也没有找到,如何知道该属性,它必须返回几个文件夹,然后找到HomeController。
我的解决办法是这样的:
这里是我的HomeController中的方法:
[HttpGet]
public ActionResult GetRandomFeed()
{
Item i = ss.getRandomFeed();
return Json(new { Source = i.Media.Source, Avatar = i.User.Avatar, Text = i.Text, Name = i.User.Name }, JsonRequestBehavior.AllowGet);
}
我的AJAX的查看:
setInterval(function() {
$.ajax({
type: "GET",
url: '/HomeController.cs/GetRandomFeed', // Of course I have tried a lots of attempts in here
contentType: "application/json;", // Not sure about this
dataType: "json",
success: function (response) {
console.log("Success :)");
},
error: function() {
console.log("Error!");
}
});
}, 2000);
所有我想要的获取该JSON文件(或者甚至可以是字符串数组)并在成功中使用它功能。这是一个简单的幻灯片放映,JSON包含我希望每隔X秒在页面中显示的URL(只是更改该JSON文件中的图像的源)。
我找不到像这样的东西。如何正确使用该URL或者找到类似于WebForms的东西,但不能在MVC中使用它。
变更网址到''/ Home/GetRandomFeed'' –
'url:'/ Home/GetRandomFeed'' use this –
'url:'@ Url.Action(“GetRandomFeed”,“Home”)'' –