如何利用基因敲除将数据发送回控制器MVC [英] How to send data back to controller in MVC using knockout

查看:108
本文介绍了如何利用基因敲除将数据发送回控制器MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

Index.cshtml:

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的:

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

基本上这样做是从数据库加载一个人,用淘汰赛使得名字和姓氏可编辑字段。它加载的值到田间

Basically what this does is loads a person from the database and using knockout makes editable fields for the firstname and lastname. It loads the values into the fields

这工作得很好。

不过我不知道如何发布更改回控制器保存。他们将不得不反序列化,并把回模型,然后调回。不知道如何做到这一点。

However I'm not sure how to post the changes back to the controller for saving. They would have to be deserialize and put back into the model then posted back. Not sure how to do this.

任何帮助吗?

推荐答案

您可以使用淘汰赛功能 postJson 。下面的保存方法添加到您的视图模型:

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

你也可以添加按钮,您的看法:

Also you can add button to your view:

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

这篇关于如何利用基因敲除将数据发送回控制器MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆