我下面一個簡單的視頻教程Knockout.js由史蒂夫·桑德森: http://channel9.msdn.com/Events/MIX/MIX11/FRM08MVC - 結合JSON對象
在它的盡頭,他執行AJAX調用來告訴你如何利用基因敲除處理數據在服務器上。我重複他所做的一切,但由於某種原因,我的JSON對象doest正確綁定到POCO類。這是一個對象,我從視圖發送:
{"firstName":"Bartosz","lastName":"Malinowski","friends":[{"name":"Zofia"},{"name":"Zenon"}],"fullName":"Bartosz Malinowski"}
,然後使用此代碼的控制器來閱讀:
public JsonResult Save(Person person)
{
var message = string.Format("Saved {0} {1}", person.firstName, person.lastName);
return Json(new { message });
}
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string fullName { get; set; }
public ICollection<Friend> friends { get; set; }
}
public class Friend
{
public string Name { get; set; }
}
}
我在客戶端的代碼如下所示:
'@{
ViewBag.Title = "Home Page";
}
<script src="../../Scripts/jquery.tmpl.js" type="text/javascript"></script>
<p>First name: <input data-bind="value: firstName"/></p>
<p>Last name: <input data-bind="value: lastName"/></p>
<p>Full name: <span data-bind="text: fullName"></span></p>
<h2>Friends (<span data-bind="text: friends().length"></span>)</h2>
<ul data-bind="template: { name: 'friendsTemplate', foreach: friends }"></ul>
<script id="friendsTemplate" type="text/html">
<li>
<input data-bind="value: name"/>
<button data-bind="click: remove">Remove</button></li>
</script>
<button data-bind="click: addFriend, enable: friends().length < 5">Add Friend</button>
<button data-bind="click: save">Save</button>
<script type="text/javascript">
function friend(name) {
return {
name: ko.observable(name),
remove: function() {
viewModel.friends.remove(this);
}
};
}
var viewModel = {
firstName: ko.observable("Bartosz"),
lastName: ko.observable("Malinowski"),
friends: ko.observableArray([new friend("Zofia"), new friend("Zenon")]),
addFriend: function() {
this.friends.push(new friend("Jan"));
},
save: function() {
$.ajax({
url: "@Url.Action("Save")",
type: "post",
data: ko.toJSON(this),
contenttype: "application/json",
success: function (result) { alert(result.message) }
});
}
};
viewModel.fullName = ko.dependentObservable(function() {
return this.firstName() + " " + this.lastName();
}, viewModel);
ko.applyBindings(viewModel);
</script>
當我在調試模式下運行它並檢查Save方法參數中的人時,我已經爲每個Person屬性獲得了空值。所以它只是不綁定我?
你能告訴我們更多的代碼嗎? – gdoron
另外,當你說'doest正確地綁定到POCO類'時,這是否意味着某些字段綁定? –
感謝您的回答,我已將我的代碼從客戶端添加到原始問題。 – Bartosz