Why after clickin on the button it display's nothing. And it do not invoke BooksByPublisherId. What i missed? How to fix this?
Controller
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);
}
}
Model
public class BookModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public decimal Price { get; set; }
}
View
@{
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")'idvariable defined and initialized t to a value before using it. Other than that, the code looks fine. Also as Stephen mentioned, Always use the helper methods to generate the proper relative url's to your action method. If your js code is inside an external js file, Use the approach mentioned in this answerdatainsuccessevent in console view byconsole.log(data)so that it can be diagnosed easily