Stop writing render code in multiple places in your ASP.NET MVC ajax applications. Learn how to push your model to the browser and use jQuery to bind it to templates.
Back in July 2009, I wrote a post: using partial views for dynamic JavaScript rendering. At the end of that post I mentioned that I would write about alternate approach – it took a while, but here it is.
The purpose of the July 2009 post was to unify rendering logic in one place for ajax applications – instead of having a version of the logic in both the view and the JavaScript. In the example, we unified a partial view and returned its result for new entities that were created. I used jQuery to append the markup as needed. However to do this, a post back to the server was required each time a new entity was created.
While that method works, I don’t use it anymore. Now, I put my ajax rendering logic on the client.
The advantages are:
- No post back requirement
- Client is in a disconnected state until the save action
First, let’s define a simple model to work with: a person with a first name, last name and age:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
To keep this sample simple, mock data storage in the controller:
static List<Person> _people = new List<Person>() {
new Person() { FirstName = "Nick", LastName = "Riggs", Age = 30 },
new Person() { FirstName = "Jack", LastName = "Smith", Age = 32 },
new Person() { FirstName = "Stacie", LastName = "Johnson", Age = 28 }
};
In the controller return an IEnumerable of Person:
[HttpGet]
public ActionResult Index()
{
return View(_people.ToArray());
}
Before passing the model to the view, convert the model to Json and include the JSON in a JavaScript variable. To do this, create an extension method:
public static string ToJson(this object @object)
{
return (new JavaScriptSerializer()).Serialize(@object);
}
Now, render the initial model in the view:
<script type="text/javascript">
var people = <%= Model.ToJson() %>;
</script>
I’m using jQuery as my scripting framework. There are several templating plugins for jQuery. For this post, I’ll be using the proposed templating solution from Microsoft for jQuery. My template looks like this:
<script id="personTemplate" type="text/html">
<div class="person">
{{= FirstName }} {{= LastName }}
<span class="detail">Age: {{= Age }}</span>
</div>
</script>
Time to get into some jQuery. The following code uses the render() method to bind the template to the data. Then appends the result to a container div:
var render = function (model) {
$("#personTemplate").render(model).appendTo($("#peopleContainer"));
};
render(people);
Quick review of what we have accomplished so far.
- Take a model from the server side
- Convert it into a JavaScript object
- Bind it to a client side template

Now it’s time to add the ability to create new people. Here is the markup for our view:
<div id="addNewContainer">
<div>
<label>First Name:</label>
<input id="firstNameInput" type="text" />
</div>
<div>
<label>Last Name:</label>
<input id="lastNameInput" type="text" />
</div>
<div>
<label>Age:</label>
<input id="ageInput" type="text" />
</div>
<div>
<button id="addNewButton">Add New Person</button>
</div>
</div>
Next, handle the addNewButton’s click.
We are going to:
- Create a JavaScript object for the new person
- Add the new person to the existing people array
- Render the new person using our template
$("#addNewButton").click(function () {
var person = {
FirstName: $("#firstNameInput").val(),
LastName: $("#lastNameInput").val(),
Age: parseInt($("#ageInput").val())
};
people.push(person);
render(person);
});
To actually save, a little more markup is needed in the view:
<div> <button id="saveButton">Save People</button> </div>
Next, create a new Action in our controller to handle the save:
[HttpPost]
public void Save(IEnumerable<Person> people)
{
_people.AddRange(people.Except(_people));
}
For converting the JavaScript objects into a post that MVC can bind to the controller, we are going to use my postify.js plugin I wrote back in August 2009. Postify will make handling the saveButton’s click straight forward:
$("#saveButton").click(function () {
$.post("/Home/Save", $.postify(people), function (result, status) {
if (status == "success")
window.alert("Saved!");
else
window.alert("Something went wrong.");
});
});
The final result:

That’s it! I find this approach is great for applications where I’m doing a lot of client side manipulation of the model.

[...] the model (database) on each edit to keep the state in sync. In a future post, I’ll discuss Here is another method that allows for one code base for rendering, without the mentioned short [...]
May 25, 2010 4:11 pm
Good stuff, Nick. Any idea how close the proposed templating solution is to becoming firm/finalized?
May 27, 2010 7:13 am
Not sure of a date – but I think it won’t be long. jQuery and Microsoft are committed to working together on this and have separate forks of the code on github. I am personally using Microsoft’s proposed solution in a production app. Also check out Microsoft’s proposed data linking for jQuery – it’s pretty nice.
May 27, 2010 7:18 am
This will work only for content that is not important for google indexing since google crawler cannot run javascript.
May 31, 2010 8:50 am
@Alex. Yeah, this is a method I use for web applications – not so much for content-based web sites.
May 31, 2010 2:51 pm
Works beautifully.
July 1, 2010 10:33 pm