我在我的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」)'' –