Render Your Model With Client Side jQuery Templates Instead of ASP.NET MVC Partial Views

Published on Author nickriggs69 Comments

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:

  1. No post back requirement
  2. 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.

  1. Take a model from the server side
  2. Convert it into a JavaScript object
  3. 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:

  1. Create a JavaScript object for the new person
  2. Add the new person to the existing people array
  3. 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.

Full Source Code

69 Responses to Render Your Model With Client Side jQuery Templates Instead of ASP.NET MVC Partial Views

  1. Good stuff, Nick. Any idea how close the proposed templating solution is to becoming firm/finalized?

  2. 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.

  3. I tried to use the above code but with Razor syntax. However I am getting a JavaScript error at the line:

    @(Model.ToJson());

    The error displays “Message: Expected identifier, string or number Line: 64 Char: 18 Code: 0 URI: localhost/MyWebApplication/”. Any idea.

  4. Ashish (and others that will run into similar problem):
    The change in MVC 3 is the introduction of HtmlString and the fact that strings are automatically mangled. You need to change helper method:

    public static HtmlString ToJson(this object value) {
    return new HtmlString((new JavaScriptSerializer()).Serialize(value));
    }

  5. Do you have a spam problem on this site; I also am a blogger,
    and I was curious about your situation; many of us have created some nice methods and we are looking to swap methods with others, why not shoot me an email if interested.

  6. Hey there! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted
    keywords but I’m not seeing very good results. If you know
    of any please share. Kudos!

  7. I just like the valuable information you provide on your articles.
    I’ll bookmark your weblog and test once more here regularly.

    I am slightly certain I will be informed lots of new stuff right right here!
    Good luck for the following!

    My web blog – web page (Christin)

  8. Hello there I am so excited I found your web site, I really found you by error, while I was browsing on Askjeeve for something else, Anyways I am here now
    and would just like to say thanks for a incredible post and a all round entertaining blog (I also love the theme/design), I
    don’t have time to browse it all at the minute but I
    have book-marked it and also added in your RSS
    feeds, so when I have time I will be back to read more, Please do keep up the excellent work.

    Visit my site; Small Removals Ipswich

  9. Good day I am so glad I found your web site, I really found you by mistake,
    while I was researching on Bing for something else,
    Nonetheless I am here now and would just like to say many thanks for
    a tremendous post and a all round exciting blog (I also love the theme/design),
    I don’t have time to read it all at the moment but I have book-marked it and also
    added in your RSS feeds, so when I have time I will be back to read more,
    Please do keep up the fantastic job.

    Here is my weblog your lawyers

  10. Proposals generally follow a four-part structure:
    1) an introduction of yourself and your proposal,
    2) a summary of the situation and needs, followed by 3)
    descriptions of the ideas or the properties or services you are offering, including all the important details and associated costs.
    The Central Avenue business corridor faces challenges of aging buildings,
    not designed for modern demands of technology and parking.
    After spending $1,000’s on courses and seminars that did not work (and were nothing more
    than sales pitches for more product, he finally decided enough was enough and release his own Hype free Probate real estate investing course and
    software to help people succeed.

  11. As for the causes, some individuals may still find it liver injury
    leading to anger and despair, while an individual realize its
    the result of cholecystitis, and also eating too much meat can lead to the release of abnormal gastric acid.
    Prilosec is the trademark brand name identify for omeprazole, an antacid drug that suppresses or decreases the volume of gastric acid secreted in the abdomen.
    Other like to blame spicy foods such as hot curries or Cajun seasonings; others cite grapefruits, oranges and
    antacids or acid suppressors like ranitidine, omeprazole or cimetidine.

  12. Do you have a spam issue on this blog; I also am a blogger, and I was curious about your situation; we have created some nice methods and
    we are looking to exchange solutions with
    other folks, be sure to shoot me an email if interested.

  13. hello there and thank you for your info – I’ve definitely picked up anything new from right here.
    I did however expertise a few technical issues
    using this web site, as I experienced to reload the site
    many times previous to I could get it to load correctly.
    I had been wondering if your web hosting is OK? Not that I’m complaining, but slow
    loading instances times will sometimes affect your placement in google and
    can damage your high quality score if advertising and marketing with
    Adwords. Anyway I am adding this RSS to my e-mail and
    could look out for a lot more of your respective intriguing
    content. Ensure that you update this again soon.

    Look at my web blog; webpage

  14. I leave a response each time I especially enjoy a post on a site or I
    have something to contribute to the discussion. Usually it’s caused by the sincerness displayed in the article
    I browsed. And on this article Render Your Model With Client Side jQuery Templates Instead of
    ASP.NET MVC Partial Views – Nick Riggs, Web Developer.
    I was actually excited enough to drop a commenta response 🙂 I actually do have 2 questions for you if it’s okay.
    Could it be only me or do some of these comments come across like
    left by brain dead folks? 😛 And, if you are posting at other online social sites,
    I would like to keep up with anything fresh you have to post.

    Would you make a list the complete urls of your community sites like your twitter feed, Facebook
    page or linkedin profile?

    Feel free to visit my web page – video professional; Violet,

  15. Undeniably believe that which you stated. Your favorite
    reason appeared to be on the internet the simplest thing to be aware of.
    I say to you, I certainly get annoyed while people consider worries that they just don’t know
    about. You managed to hit the nail upon the top and defined out the whole thing without having side-effects , people could take a signal.
    Will probably be back to get more. Thanks

    Look at my web-site: wordpress (Alfonzo)

  16. It’s a shame you don’t have a donate button! I’d certainly donate to this superb
    blog! I guess for now i’ll settle for book-marking and adding your RSS
    feed to my Google account. I look forward to new updates and will share this blog with my Facebook group.
    Chat soon!

  17. Aw, this was an incredibly good post. Spending some time and actual
    effort to generate a superb article… but what can I say… I put things ooff a whole lot and never manage to get nearly anything done.

  18. Ηi ther this is kind of of off topic but I was wanting
    to know іf Ьloցs use WYSIWYG editors or if yoս have to manuallү code with HTML.

    I’m starting a blog soon but have no coding skills so I
    wanted to get aɗvice from someone with experience.Any
    help would be greatly appreciated!

  19. Hiya! Quick question that’s totally off topic.
    Do you know how to make your site mobile friendly?
    My blog looks weird when browsing from my iphone4.

    I’m trying to find a theme or plugin that might be able to correct this issue.
    If you have any suggestions, please share. Thank you!

  20. Great post. I was checking continuously this blog and I’m impressed!
    Extremely helpful info particularly the last part 🙂 I care for such info much.

    I was seeking this particular information ffor a very long time.
    Thank yyou and best of luck.

    Feel free to surf to my weeb site :: quote, Reyes,

  21. Exclu concédé, un quiconque altérée cohabiterait apaisé
    quand bizarre sacoche guérissait Participé chuintant du entrée Comme cette accrédité pour l’étape, au digression de même éviter au comédie convaincus imprégnées

Leave a Reply

Your email address will not be published. Required fields are marked *