JQuery の getJSON メソッドを使用して、MVC コントローラーからデータを取得しています。
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetContacts(int? numberOf)
{
List<Contact> contacts =
(numberOf != null && numberOf > 0) ?
_provider.GetContacts(Convert.ToInt32(numberOf)):
_provider.GetContacts();
return Json(contacts);
}
アイデアは、このコントローラーメソッドを使用して、すべての連絡先、または「numberOf」が指定されている場合は特定の数の連絡先を提供できるということです。
問題は、"Contacts/GetContacts/5" に GET 要求を送信すると、コントローラーの "numberOf" が常に null になることです。ただし、「Contacts/GetContacts/?numberOf=5」に GET リクエストを送信すると、期待どおりに動作します。
それが役立つ場合は、JavaScript メソッドを次に示します。
getContacts: function(numberOf){
var path = "/Contact/GetContacts/";
path = (numberOf<=0) ? path : "/Contact/GetContacts/" + numberOf;
$.getJSON(path, null,
function(json){
$.each(json, function(){
$('tbody','#contacts').append(
"<tr id=\"contact-"+ this.Id +"\">"
+ "<td>"+ this.Id +"</td>"
+ "<td>"+ this.FirstName +"</td>"
+ "<td>"+ this.LastName +"</td>"
+ "</tr>"
);
});
});
},