I have the following code:
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();
}
}
}
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
This works fine.
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.
Any help?
You can use knockout function
postJson
. Add the following Save method to your view model:Also you can add button to your view: