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.FirstName));
alert(initialData);
// The *viewmodel* - JavaScript that defines data and behavior of the UI
function AppViewModel() {
this.firstName = ko.observable(initialData);
// this.lastName = ko.observable("Bertington");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
var people = new PeopleEntities();
var person = people.People.First();
return View(person);
}
}
Basically what this does is loads a person from the database and using knockout makes an editable field for the first name and loads the FirstName into it.
This works fine, however, I also want to load the LastName. I’m unsure how to do this because I’m serializing just the first name. I’m thinking I want to serialize the whole model but am not sure how I would then get access to each name.
The
JavaScriptSerializerconverts an object to a JSON string. If you serialize the entire model you can then access its fields the same way you do in C# using the dot notation more specificallyinitialData.FirstNameandinitialData.LastName.This works because
initialDatacontains a javascript object initialized from the JSON string obtained from the serializer. If the model contained only the first and last name properties this would be the string generated by the serializer: