Skip to content

Instantly share code, notes, and snippets.

@jasonmitchell
Created December 8, 2013 14:33
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/7858340 to your computer and use it in GitHub Desktop.
Save jasonmitchell/7858340 to your computer and use it in GitHub Desktop.
@model Quickstart.Web.Models.Person
@section scripts
{
<script type="text/javascript" src="/Scripts/ViewModels/AjaxModelLoading.js"></script>
<script type="text/javascript">
var viewModel = new AjaxModelLoading("@Url.Action("AjaxModelLoading")");
ko.applyBindings(viewModel);
viewModel.getRandomModel();
</script>
}
<h2>Ajax Model Loading Sample</h2>
<div data-bind="if: isLoading()">
Loading...
</div>
<div data-bind="if: isLoaded()">
<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>
</div>
<a href="#" data-bind="click: getRandomModel">Get random person</a>
var AjaxModelLoading = function(url) {
var self = this;
self.isLoaded = ko.observable(false);
self.isLoading = ko.observable(false);
self.getRandomModel = function () {
self.isLoading(true);
self.isLoaded(false);
// Setting a timeout so the loading text is visible in the sample
setTimeout(function() {
$.ajax(url, {
type: "GET",
cache: false,
}).done(function(data) {
ko.mapping.fromJS(data, {}, self);
self.isLoaded(true);
self.isLoading(false);
});
}, 1000);
};
};
public class JsonNetResult : ActionResult
{
private const string ContentType = "application/json";
private readonly object data;
private readonly Formatting formatting;
private readonly JsonSerializerSettings serializerSettings;
public JsonNetResult(object data)
{
this.data = data;
formatting = Formatting.None;
serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = ContentType;
if (data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = formatting };
JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
serializer.Serialize(writer, data);
writer.Flush();
}
}
public object Data
{
get { return data; }
}
}
public class SampleController : Controller
{
public ActionResult AjaxModelLoading()
{
Person model = CreateRandomModel();
if (Request.IsAjaxRequest())
{
return new JsonNetResult(model);
}
return View(model);
}
private static Person CreateRandomModel()
{
Random random = new Random();
string[] firstNames = { "Jason", "John", "Dave", "Steve" };
string[] lastNames = { "Mitchell", "Brown", "White", "Smith" };
string firstName = firstNames[random.Next(firstNames.Length)];
string lastName = lastNames[random.Next(lastNames.Length)];
return new Person
{
FirstName = firstName,
LastName = lastName,
EmailAddress = string.Format("{0}@{1}.com", firstName, lastName),
PhoneNumber = random.Next(int.MaxValue).ToString("D10"),
DateOfBirth = DateTime.Today.AddYears(random.Next(-50, -10))
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment