1
爲什麼在點擊按鈕後顯示什麼都沒有。它不會調用BooksByPublisherId
。我錯過了什麼?如何解決這個問題?使用ajax顯示列表
控制器
public class FoodController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult BooksByPublisherId(int id)
{
IList<BookModel> modelList = new List<BookModel>();
modelList.Add(new BookModel { Author = "Jhon", Year = "1970" });
modelList.Add(new BookModel { Author = "Nick", Year = "1977" });
modelList.Add(new BookModel { Author = "Joseph", Year = "1978" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
型號
public class BookModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public decimal Price { get; set; }
}
查看
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<button data-bind="click: capitalizeLastName">Load list</button>
<div class="results">Wait for list</div>
<script>
function AppViewModel() {
this.capitalizeLastName = function() {
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
success: function (data) {
var result = "";
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br />' +
'<b> Author :</b>' + book.Author + '<br />' +
'<b> Year :</b>' + book.Year + '<br />' +
'<b> Price :</b>' + book.Price + '<hr />';
});
$('.results').html(result);
},
error: function (response) {
debugger;
alert('eror');
}
});
}
}
ko.applyBindings(new AppViewModel());
</script>
您在瀏覽器控制檯中遇到什麼錯誤?並使用'@ Url.Action(「BooksByPublisherId」,「Food」)' –
正確地生成URL。我看到的唯一問題是在使用它之前,我沒有看到'id'變量被定義並初始化爲一個值。除此之外,代碼看起來很好。同樣如Stephen所說,總是使用助手方法爲您的操作方法生成適當的相對url。如果你的js代碼在一個外部的js文件中,請使用這個[answer]中提到的方法(http://stackoverflow.com/questions/34360537/how-do-i-make-js-know-about-the-application -root/34361168#34361168) – Shyju
通過'console.log(data)'給我們顯示'console'中的'success'事件中的'data',以便它可以被輕鬆診斷 – anand