2012-08-09 4 views
1

를 사용하여 MVC에서 컨트롤러에 다시 데이터를 전송하는 방법 :나는 다음과 같은 코드를 한 녹아웃

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

Index.cshtml

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에 대한 편집 가능 필드를 만듭니다. 필드에 값을로드합니다.

괜찮습니다.

그러나 저장을 위해 변경 사항을 다시 컨트롤러에 게시하는 방법을 모르겠습니다. deserialize하고 다시 모델에 넣은 다음 다시 게시해야합니다. 이 작업을 수행하는 방법을 잘 모릅니다.

어떤 도움이 필요합니까?

답변

9

녹아웃 기능 postJson을 사용할 수 있습니다. 뷰 모델에 다음과 같은 저장 방법을 추가

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>