MVC3 jQuery templates

2019-08-05 07:55发布

问题:

I'm trying to learn how to use jQuery templates using this old ScottGu's blog post:

http://weblogs.asp.net/scottgu/archive/2010/05/07/jquery-templates-and-data-linking-and-microsoft-contributing-to-jquery.aspx

And the plugin from here:

https://github.com/jquery/jquery-tmpl/blob/master/jquery.tmpl.min.js

But either I'm doing something wrong, or this article isn't relevant anymore.

Could you show me a better and up-to-date one?

回答1:

I wrote a blog post about jQuery templates a week or so ago. There's no special magic in getting it to work with MVC - just make sure you're returning a JSON/XML object and are referencing the correct data and it's all straightforward. You should check to make sure your templates are matching up with the data being returned by your controller method.

From your comment above it actually sounds like your issue lies in referencing the jquery-tmpl file before you reference the jquery file in your header.



回答2:

As I found cool things that ScottGu described in that article still in beta, but you can already use them and it's cool!

here is an update snippet, that works:

<script type="jquery/x-jquery-tmpl" id="contactTemplate" >
  <div>
        Name: {{= name }} <br/>
        Phone: {{= phone }}
  <div>
</script>

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.tmpl.min.js")" ></script>

<script type="text/javascript">
    var contact = { name: 'Scott Guthrie', phone: '31415' };

    $(document).ready(function() 
    {
        $('#contactTemplate').tmpl(contact).appendTo('#contactContainer');
    });
</script>

As you can see .render() method changed to .tmpl() and instead of an array I'm passing a single object.