Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Last active December 23, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonmitchell/6608081 to your computer and use it in GitHub Desktop.
Save jasonmitchell/6608081 to your computer and use it in GitHub Desktop.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Quickstart.Web.Extensions
{
public static class ObjectExtensions
{
public static string ToJson(this object obj)
{
JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings);
}
}
}
using System;
namespace Quickstart.Web.Models
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
}
}
using System;
using System.Web.Mvc;
using Quickstart.Web.Models;
namespace Quickstart.Web.Controllers
{
public class SampleController : Controller
{
public ActionResult SimpleModelLoading()
{
Person model = new Person
{
FirstName = "Jason",
LastName = "Mitchell",
EmailAddress = "contact@jason-mitchell.com",
PhoneNumber = "0123456789",
DateOfBirth = DateTime.Today.AddYears(-25)
};
return View(model);
}
}
}
@using Quickstart.Web.Extensions
@model Quickstart.Web.Models.Person
@section scripts
{
<script type="text/javascript" src="/Scripts/ViewModels/SimpleModelLoading.js"></script>
<script type="text/javascript">
var viewModel = new SimpleModelLoading(@Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
</script>
}
<h2>Simple Model Loading Sample</h2>
<div>
<label>First Name:</label>
<input type="text" data-bind="value:firstName"/>
</div>
<div>
<label>Last Name:</label>
<input type="text" data-bind="value: lastName"/>
</div>
<div>
<label>Email Address:</label>
<input type="text" data-bind="value: emailAddress"/>
</div>
<div>
<label>Phone Number:</label>
<input type="text" data-bind="value: phoneNumber"/>
</div>
<div>
<label>Date of Birth:</label>
<input type="text" data-bind="value: dateOfBirth"/>
</div>
var SimpleModelLoading = function (data) {
var self = this;
self.firstName = ko.observable(data.firstName);
self.lastName = ko.observable(data.lastName);
self.emailAddress = ko.observable(data.emailAddress);
self.phoneNumber = ko.observable(data.phoneNumber);
self.dateOfBirth = ko.observable(data.dateOfBirth);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment