ASP.NET MVC with JTemplates – Part II

In my first part I of this two part series, I covered using Json, ASP.NET MVC, and jTemplate to bind to a simple html table.

The next part of this series is to ‘prettify’ the table using the jQuery plugin  DataTables

DataTables supports using the same theme as used by jQuery UI, so I have decided to include this as well.  Basically in about 4 lines of javascript, we can convert the previous simple table to a nice looking pageable, sortable, searchable grid!

image

The references are updated (see sample code):

    <link href="<%= Url.Content("~/Content/Site.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/jquery-ui-1.8.1.custom.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/demo_table_jui.css") %>" 
      rel="stylesheet"  type="text/css" />
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-ui.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-jtemplates_uncompressed.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery.dataTables.js") %>"></script>

The next step is to apply the DataTables plugin to our table.

(If you had the demo code for part I, you might notice part II I had to make sure to define the thead and tbody tags in the table.)

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type:"POST",
            url: "<%= Url.Action("GetData") %>",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                $("#jTemplateDemo").processTemplate(data);

                $('#personTable').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "aoColumns": [{ "sTitle": "First Name" },                                   
                       { "sTitle": "Email" }]
                });
            }
        });
    });
</script>

I have included the previous javascript – the key section is the $(‘#personTable’).dataTable.

There are tons more functionality you can get from the plugin – including grid editing, server pagination, etc…  (ie. saving state – (“bStateSave”:true)

I hope to create a third part of this series that will combine the edit features of the datatable with the ASP.NET MVC + json capability.  This will be valuable to show the posting of json data as well as updating the underlying json data source for the template.

(by the way, there is an unintended “easter egg” in this post.  If you recall the template grid TH was incorrectly labeled ‘Last Name’ instead of ‘Email’. By defining the aoColumns above, it overrides the ‘Last Name’ in the template and applies the ‘Email’ header.  aoColumns is an optional parameter in this case).

I have included this code for your review – download here

Advertisements

ASP.NET MVC with JTemplates – Part II

In my first part I of this two part series, I covered using Json, ASP.NET MVC, and jTemplate to bind to a simple html table.

The next part of this series is to ‘prettify’ the table using the jQuery plugin  DataTables

DataTables supports using the same theme as used by jQuery UI, so I have decided to include this as well.  Basically in about 4 lines of javascript, we can convert the previous simple table to a nice looking pageable, sortable, searchable grid!

image

The references are updated (see sample code):

    <link href="<%= Url.Content("~/Content/Site.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/jquery-ui-1.8.1.custom.css") %>" 
      rel="stylesheet" type="text/css" />
    <link href="<%= Url.Content("~/Content/demo_table_jui.css") %>" 
      rel="stylesheet"  type="text/css" />
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-1.4.1.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-ui.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery-jtemplates_uncompressed.js") %>"></script>
    <script type="text/javascript" 
      src="<%= Url.Content("~/Scripts/jquery.dataTables.js") %>"></script>

The next step is to apply the DataTables plugin to our table.

(If you had the demo code for part I, you might notice part II I had to make sure to define the thead and tbody tags in the table.)

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type:"POST",
            url: "<%= Url.Action("GetData") %>",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                $("#jTemplateDemo").processTemplate(data);

                $('#personTable').dataTable({
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "aoColumns": [{ "sTitle": "First Name" },
                       { "sTitle": "Email" }]
                });
            }
        });
    });
</script>

I have included the previous javascript – the key section is the $(‘#personTable’).dataTable.

There are tons more functionality you can get from the plugin – including grid editing, server pagination, etc…  (ie. saving state – (“bStateSave”:true)

I hope to create a third part of this series that will combine the edit features of the datatable with the ASP.NET MVC + json capability.  This will be valuable to show the posting of json data as well as updating the underlying json data source for the template.

(by the way, there is an unintended “easter egg” in this post.  If you recall the template grid TH was incorrectly labeled ‘Last Name’ instead of ‘Email’. By defining the aoColumns above, it overrides the ‘Last Name’ in the template and applies the ‘Email’ header.  aoColumns is an optional parameter in this case).

I have included this code for your review – download here

ASP.NET MVC with jTemplates – Part I

One of my goals in web development is to continue to look to use json to transmit data vs. using partial views.  Obviously by transmitting json data, the payload is going to be much more efficient.

I’m going to break this out into two parts :

Part I is going to cover the basics to using jTemplate with jQuery within an asp.net mvc environment.

Part II is going to take this concept and apply it to a nice looking jQuery plugin ‘grid control’ called  DataTables

Let’s look at what the final result will be:

image

Let’s address the server side pieces first:

I’m going to create a new Model class ‘Person’:

public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }

Using the default asp.net mvc created project type, I’ll just a hook into the the Home controller to display the table in the index page.  To do this, I’ll need to add another action with some sample data that will be called from the page via ajax:

 

 [HttpPost]
 public JsonResult GetData()
 {
      IList<Person> people = new List<Person>
        {
          new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com"},
          new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com"},
          new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com"},
          new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com"},
          new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com"}
        };
      return Json(people);
}

The ‘return Json(people)’ will return the list in json format – which you can see in the above Firebug screenshot ‘response’. 

So that is basically it for the server side.

The first step in the views is to add the references to the javascript files.  Since I’m using the site.master I’ll add it there, so that it’s available to other views as well:

image 

(For production, you will want to use the compressed/min files instead)

I also add a new ContentPlaceHolder in the head of the site.master:

<asp:ContentPlaceHolder ID="HeadContent" runat="server" />

This way on the views, I can put any scripts in the head tags as well.

In the Index.aspx page we can finish this functionality:

1. add the scripts to the head of the view:

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
        $.ajax({
                type:"POST",
                url: "<%= Url.Action("GetData") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                    $("#jTemplateDemo").processTemplate(data);
                }
            });
        });
    </script>
</asp:Content>

To review this (we could use a $.getJSON as well) – on the page ready function I’m going to make an ajax call back to the ‘GetData’ action.  This is defined in the ‘url:’ parameter.

In this case there are no parameters being passed so the data is left blank (this is best practice to include “{}” when blank).  It is possible to use a REST url as well with parameters.

We define out contentType (using $.getJSON) would do this automatically.

Lastly, we provide an ‘onSuccess’ function – the ‘data’ will contain the returning Json from our action call.  The next two calls use the jTemplate API to merge the Json data to the templated html, as shown below.

2. add the template to the view:

<script type="text/html" id="templateHolder">
    <table border="1">
    <tr>
        <th>
            First Name
        </th>
        <th>
            Email
        </th>
    </tr>
    {#foreach $T as record} 
        <tr>
            <td>
                {$T.record.FirstName}
            </td>
            <td>
                {$T.record.Email}
            </td>
        </tr>
    {#/for}
</table>
</script>
    
<div id="jTemplateDemo">
</div>

 

One thing to keep in mind is to put this html in the script tag.  Alternatively you could load this template from another file as well.

With this approach we have created a very lightweight approach to passing data from the server to the client – the binding to the template occurs on the client.  If we used partial views, the binding process would occur on the server and transmit the payload with the html, increasing it’s size.  The lightweight json approach is critical especially in our ajax calls

Next post we’ll take this table and convert it into a ‘DataTable’.

I have included this code for your review – download here

ASP.NET MVC with jTemplates – Part I

One of my goals in web development is to continue to look to use json to transmit data vs. using partial views.  Obviously by transmitting json data, the payload is going to be much more efficient.

I’m going to break this out into two parts :

Part I is going to cover the basics to using jTemplate with jQuery within an asp.net mvc environment.

Part II is going to take this concept and apply it to a nice looking jQuery plugin ‘grid control’ called  DataTables

Let’s look at what the final result will be:

image

Let’s address the server side pieces first:

I’m going to create a new Model class ‘Person’:

public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
    }

Using the default asp.net mvc created project type, I’ll just a hook into the the Home controller to display the table in the index page.  To do this, I’ll need to add another action with some sample data that will be called from the page via ajax:

 

 [HttpPost]
 public JsonResult GetData()
 {
      IList<Person> people = new List<Person>
        {
          new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com"},
          new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com"},
          new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com"},
          new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com"},
          new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com"}
        };
      return Json(people);
}

The ‘return Json(people)’ will return the list in json format – which you can see in the above Firebug screenshot ‘response’. 

So that is basically it for the server side.

The first step in the views is to add the references to the javascript files.  Since I’m using the site.master I’ll add it there, so that it’s available to other views as well:

image 

(For production, you will want to use the compressed/min files instead)

I also add a new ContentPlaceHolder in the head of the site.master:

<asp:ContentPlaceHolder ID="HeadContent" runat="server" />

This way on the views, I can put any scripts in the head tags as well.

In the Index.aspx page we can finish this functionality:

1. add the scripts to the head of the view:

<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
        $.ajax({
                type:"POST",
                url: "<%= Url.Action("GetData") %>",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                    $("#jTemplateDemo").setTemplate($("#templateHolder").html());
                    $("#jTemplateDemo").processTemplate(data);
                }
            });
        });
    </script>
</asp:Content>

To review this (we could use a $.getJSON as well) – on the page ready function I’m going to make an ajax call back to the ‘GetData’ action.  This is defined in the ‘url:’ parameter.

In this case there are no parameters being passed so the data is left blank (this is best practice to include “{}” when blank).  It is possible to use a REST url as well with parameters.

We define out contentType (using $.getJSON) would do this automatically.

Lastly, we provide an ‘onSuccess’ function – the ‘data’ will contain the returning Json from our action call.  The next two calls use the jTemplate API to merge the Json data to the templated html, as shown below.

2. add the template to the view:

<script type="text/html" id="templateHolder">
    <table border="1">
    <tr>
        <th>
            First Name
        </th>
        <th>
            Email
        </th>
    </tr>
    {#foreach $T as record}
        <tr>
            <td>
                {$T.record.FirstName}
            </td>
            <td>
                {$T.record.Email}
            </td>
        </tr>
    {#/for}
</table>
</script>

<div id="jTemplateDemo">
</div>

 

One thing to keep in mind is to put this html in the script tag.  Alternatively you could load this template from another file as well.

With this approach we have created a very lightweight approach to passing data from the server to the client – the binding to the template occurs on the client.  If we used partial views, the binding process would occur on the server and transmit the payload with the html, increasing it’s size.  The lightweight json approach is critical especially in our ajax calls

Next post we’ll take this table and convert it into a ‘DataTable’.

I have included this code for your review – download here

WebHost4Life

I’m a truly dedicated WebHost4Life fan.  Been using them for something like 8 years now ? They were always responsive to any request, and they even allowed me to make some exceptions (I had a program I needed to be able to run on the server).

The control panel, although not the prettiest thing, got the job done.

Let me step back one moment and say they were advertising and telling me about how they were upgrading their system and all the improvements and ease of use and performance it would bring. I was looking forward to it.  It was delayed I noticed when I’d come to the site, but it would say they are ‘testing everything’.  That made me feel better about it all as well.

Well… I felt that way until 3 weeks ago. 3 weeks ago, without warning they flipped the switch.

Day 1: the forum I used for my community (MYSQL) was practically unusable.  Extremely slow. So badly I couldn’t even post to the community that there was a problem.  I entered a ticket, it took escalating the ticket 3 times.  5 days later it was working.  It’s still much slower than before.  5 days.

When I would chat or get a ticket I started noticing a trend… every single correspondance was ‘I’m sorry for the inconvenience this has caused you…’.  Like it was the scripted response to everything.

But ok, that was fine until I went to my .net main site that uses MSSQL. Hmmm, I track and store data and noticed the last data entry was a month ago.  One month behind.  All the data for the last month was gone.  What???  Another ticket.  Another 5 days. I never got a response.  They literally never answered.  They had no backup to offer me.  Data was gone, forever.

The best answer I got was ‘I’m sorry for the inconvenience this has caused you’.

But wait, it gets better. Remember how they were so good to work with on running my program I need ?  Despite everything I said, they flat out refused ‘it’s against our policy’.  I’m like ‘I’ve been running this safely for 8 years ???’.  Didn’t matter.  I asked to talk to manager.  They said ‘ok’. Ticket sat in the queue for 3 more days.

Three days later, I responded, asking what the status is.  Same response – ‘it’s against our policy’ – it wasn’t from a manager either.

Let’s talk about the control panel.. it’s pretty.  Pretty slow.  Pretty useless.  I need to backup my database (since they can’t migrate it properly), but the tool throws some .net exception on the webpage.  Customer support said ‘try Firefox’. Same error.

This is twice in 3 weeks I had to open a ticket for a buggy control panel that throws exceptions.

Lastly, I have a requirement to upload files.  So I have to set permissions.  They said ‘add a new user’.  I said ‘no this is the internet user’ .  The old ‘ugly’ control panel handled all this fine and perfectly.  The new tool… timed out.  The final ticket response was ‘use your FTP program to change permissions’.

I should add, I have lost 80% of my community. They were all very disapointed to find out the data was gone.  The forum they meet and talk and plan events was unusable.  The program I run can’t be run so the events can’t run.  I have to re-code the app now (it was given to me, no source code).

I’m writing this because as a consumer, I really feel I’ve been thrown and tossed around by a company that doesn’t respect a loyal customer.  Who must be too big now to value guys like me.  Back ‘in the day’ I suspect they worked well with me because they were a good company.  Something has changed.

I highly suggest – don’t use Webhost4life.  You will regret it.

So, needless to say, I’m looking for a new host.  One of the things I liked about Webhost4life was that I could run my mysql blog and forum as well as my .net site.  It ‘was’ easy to manage.  Secondly they don’t charge for bandwith usage.  I don’t use too much, but I had confort knowing the bill would always be the same amount.

Quite disapointing to me in a time where companies are susposedly struggling with the economy. I would think a shift would occur where they valued their customers.  Instead, I’m just another ‘policy’ to them that pays a year in advance…

Powered by Qumana