如何使用knockout将数据发送回MVC中的控制器

时间:2012-08-09 08:43:02

标签: asp.net-mvc knockout.js

我有以下代码:

Index.cshtml:

@using System.Web.Script.Serialization
@model MvcApplication3.Models.Person

<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>

    <!-- This is a *view* - HTML markup that defines the appearance of your UI -->


<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>


<script type="text/javascript">

    var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

    // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
    function AppViewModel() {
        this.firstName = ko.observable(initialData.FirstName);
        this.lastName = ko.observable(initialData.LastName);

    }

    // Activates knockout.js
    ko.applyBindings(new AppViewModel());

</script>

HomeController中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;

namespace MvcApplication3.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var people = new PeopleEntities();

            var person = people.People.First();

            return View(person);
        }

        [HttpPost]
        public ActionResult Index(Person person)
        {
            //Save it

            return View();
        }
    }
}

基本上它的作用是从数据库加载一个人并使用knockout为firstname和lastname创建可编辑的字段。它将值加载到字段

这很好用。

但是我不确定如何将更改发布回控制器以进行保存。他们必须反序列化并重新放回模型然后回发。不知道怎么做。

任何帮助?

1 个答案:

答案 0 :(得分:9)

您可以使用淘汰赛功能postJson。将以下Save方法添加到视图模型中:

function AppViewModel() {
    self = this;

    self.firstName = ko.observable(initialData.FirstName);
    self.lastName = ko.observable(initialData.LastName);

    self.Save = function(){
        var jsonData = ko.toJSON(self);
        ko.utils.postJson(location.href, {person: jsonData});
    };
}   

您还可以在视图中添加按钮:

<button data-bind="click: Save" ></button>