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

Ano*_*use 1 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>
Run Code Online (Sandbox Code Playgroud)

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这很好用.

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

有帮助吗?

Art*_*kov 9

You can use knockout function postJson. Add the following Save method to your view model:

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});
    };
}   
Run Code Online (Sandbox Code Playgroud)

Also you can add button to your view:

<button data-bind="click: Save" ></button>
Run Code Online (Sandbox Code Playgroud)