1

我有以下代码:

索引.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>

家庭控制器:

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();
        }
    }
}

基本上,它的作用是从数据库中加载一个人,并使用敲除为名字和姓氏创建可编辑字段。它将值加载到字段中

这工作正常。

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

有什么帮助吗?

4

1 回答 1

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>
于 2012-08-09T09:25:24.437 回答