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 […]
Good stuff, Nick. Any idea how close the proposed templating solution is to becoming firm/finalized?
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.
This will work only for content that is not important for google indexing since google crawler cannot run javascript.
@Alex. Yeah, this is a method I use for web applications – not so much for content-based web sites.
Works beautifully.
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.
Issue resolved. I modified my code
@(Model.ToJson());
to
@(Html.Raw(Json.Encode(Model)));
Works like a charm.
Isn’t there a way to return a JsonResult directly to the view using this.Json(people) from the controller?
@teebot: JsonResult will result in a string containing the Json. But it won’t pass that string to the view.
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));
}
Rigs,
Good work, it is really a cool trick.
Keep posting good articles like this
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.
Avide,élégant propriété à travers fournir au-dessus volont
Yes! Finally something about wango conference.
I just like the helpful info you provide in your articles.
I’ll bookmark your weblog and take a look at once more here frequently.
I’m quite certain I will be told many new stuff right here!
Best of luck for the following!
If you are going for most excellent contents like I do, just pay a
visit this website every day as it provides quality contents, thanks
My blog … click here (http://thefrontierroom.com)
Try and match for no more than three hours daily.
Here is the easiest way to safeguard your child from unsuitable content.
Signing to play your nemesis in Japan can really bring your game to another level!
My webpage: elo Boost – gourmetguys.Co.za –
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!
It’s hard to come by experienced people in this particular subject, but you seem like you know what you’re talking about!
Thanks
Here is my page; vec veterinary emergency clinic
You really make it seem so easy with your presentation but
I find this topic to be actually something which I think I would
never understand. It seems too complicated and very broad for me.
I am looking forward for your next post, I’ll try to get the hang
of it!
Visit my weblog; spence diamonds upgrade
Your style is really unique in comparison to other people I’ve read stuff
from. I appreciate you for posting when you’ve got the opportunity, Guess I will just book mark this page.
Here is my web blog :: does spence diamonds do financing
Hello to every , since I am actually eager of reading this webpage’s post to be updated
regularly. It contains nice material.
Also visit my blog post … engagement rings
Chicken is also a very preferred ingredient to be used in different dishes.
Trans fatty acids found in margarine, some salad dressing, deli meats, baking goods and candy.
Paleo diet recipes are the Back to Mother Nature diet for the whole family.
Also visit my site … Creating your own recipe book
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)
Greetings! Very useful advice within this article! It’s the little
changes which will make the greatest changes. Many thanks for sharing!
My blog :: personal injury accident Columbia
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
My spouse and I stumbled over here from a different page
and thought I might check things out. I like what I see so i am just following
you. Look forward to looking at your web page yet
again.
It’s amazing to pay a visit this website and reading the views
of all mates regarding this piece of writing, while I am also eager of getting familiarity.
Feel free to visit my web page california
Heya i’m for the primary time here. I came across this board and
I in finding It really helpful & it helped me out
a lot. I’m hoping to offer something again and help others such
as you aided me.
Wonderful article! That is the kind of information that should be shared across the web.
Disgrace on Google for no longer positioning this post higher!
Come on over and consult with my website . Thanks =)
Feel free to visit my homepage: emergency locksmith car
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
When I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and now whenever a
comment is added I receive four emails with the exact same comment.
Is there a means you can remove me from that service?
Thanks!
Feel free to visit my blog … Digital Content Service Vancouver
It’s remarkable to pay a quick visit this site and reading the views of all friends about this paragraph,
while I am also zealous of getting experience.
Also visit my page printers for graphic designers
I am regular visitor, how are you everybody? This post posted at this web page is in fact nice.
Feel free to surf to my web-site Insects Pest Control Vancouver BC
I have been surfing online more than three hours today, yet I never found any interesting article
like yours. It’s pretty worth enough for me. Personally, if all website owners and bloggers made good content ass you did, the internet
will be much more useful than ever before.
Also visit my web blog … top rated protein powder for men
Good post. I definitely love this site. Keep writing!
my web blog … best rowing machine for home
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.
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.
It’s an remarkable piece of writing in favor of all the internet people; they will take benefit from
it I am sure.
My homepage :: test
What a material of un-ambiguity and preserveness of valuable experience about unexpected
feelings.
Also visit my blog – go to my site
Good day! I could have sworn I’ve been to your blog before but
after browsing through many of the articles I realized it’s new to me.
Regardless, I’m definitely delighted I discovered it and I’ll be book-marking it and checking back
frequently!
Also visit my web site Which Is The Best Pest Control Company Abbotsford BC
Every weekend i used to pay a visit this web page, for the reason that i wish for enjoyment, for
the reason that this this website conations actually good funny material too.
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.
Hi there Dear, are you genuinely visiting this website daily,
if so afterward you will definitely get good know-how.Throatfuck
Feel free to surf to my webpage :: online gambling
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
What’s up, after reading this awesome paragraph
i am too happy to share my know-how here with mates.
my web blog … read this
światowej szeroki
Hi! I’m at work browsing your blog from my new
apple iphone! Just wanted to say I love reading through your blog and look
forward to all your posts! Keep up the great work!
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,
You could certainly see your enthusiasm within the work you write.
The sector hopes for even more passionate writers such as you
who are not afraid to mention how they believe.
Always follow your heart.
my blog post … Dallas Texas automatic garage door opener
Good post. I learn something totally new and challenging on websites I stumbleupon everyday.
It’s always helpful to read content from other authors and
use a little something from other websites.
Feel free to surf to my blog: new port richey internet marketing
You ought to be a part of a contest for one
of the finest blogs online. I’m going to recommend this
site!
my site … web page (Teodoro)
Thanks for finally writing about > Render Your Model With Client Side jQuery Templates
Instead of ASP.NET MVC Partial Views – Nick Riggs, Web Developer < Loved it!
Here is my web-site – lawyer – Adalberto,
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)
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!
What’s up to every one, the contents existing at this website are in fact remarkable for
people experience, well, keep up the nice work fellows.
my web-site: website seo services
I’m amazed, I have to admit. Seldom do I encounter a
blog that’s both equally educative and interesting, and
without a doubt, you have hit the nail on the head.
The problem is an issue that not enough men and women are speaking intelligently about.
I’m very happy I found this during my hunt for something concerning this.
Look into my website personal injury demand letter
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.
Η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!
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!
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,
Good post! We are linking to this particularly great content on our site.
Keep up the great writing.
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
Excrétion déduis bouillonnant du — 1000 $ échec
entité
It’s going to be end of mine day, except before finish I am reading this
great piece of writing to improve my know-how.
Great post.
Hello to every , since I am in fact keen of reading this web site’s
post to be updated regularly. It carries nice data.
article bizarre, ce n’est pas Swagg Man qui a réalisé l’album a Skvllfvcked Forever mais bien c SEWER !