2016-02-20 77 views
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> 
+0

您在瀏覽器控制檯中遇到什麼錯誤?並使用'@ Url.Action(「BooksByPublisherId」,「Food」)' –

+1

正確地生成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

+0

通過'console.log(data)'給我們顯示'console'中的'success'事件中的'data',以便它可以被輕鬆診斷 – anand

回答

1

唯一的問題我可以在你的代碼中看到的是,您使用的是被稱爲id變量打造JS作爲ajax調用的數據發送的對象,但未聲明並初始化任何對象對它的價值。在這你會得到一個腳本錯誤,如

Uncaught ReferenceError: id is not defined

由於此腳本錯誤,您的其他js代碼將無法正常工作!如你所見,錯誤是自我解釋的。只需聲明一個變量id併爲其設置一些值。

var id = 911; 
$.ajax({ 
     type: "GET", 
     url: "Food/BooksByPublisherId", 
     data: { "id": id }, 
     // Your existing code 

     }); 

另外我看到你已經硬編碼了你的動作方法的路徑。更好的方法是使用Html幫助器方法(如Url.Action)來構建操作方法的正確相對路徑。

url: "@Url.Action("BooksByPublisherId","Food")", 

這將工作,如果你的js代碼是在剃刀視圖內。如果您的代碼位於外部js文件中,則可以使用this post中解釋的解決方案。