How to Add custom html to Header in WebGrid

How to make a MVC 3 Webgrid with checkbox column?
This article will show you a How to Add custom html to Header in WebGrid e.g. add a check box in webgrid header.

Some time you come across a situation where you have to add html element (checkbox) in webgrid header, consider a column with checkbox and you want to add checkbox in the header of same column.

Approach: In document.ready event find out webgrid header and replace it with html string.

     $(document).ready(function () {
         $('#gridContent table th').each(function () {
             if (this.innerHTML == "") {
                 this.innerHTML = "<input type='checkbox' id='chkHeader'  />";
             }
         });
     });

Application: If you have a checkbox column in webgrid and on clicking of header checkbox all checkbox in column will be checked.

header checkbox in webgrid

header checkbox in webgrid

 <script type="text/javascript">
     $(document).ready(function () {
         $('#gridContent table th').each(function () {
             if (this.innerHTML == "") {
                 this.innerHTML = "<input type='checkbox' id='chkHeader'  />";
             }
         });
         $('#gridContent table th input:checkbox').click(function (e) {
             var table = $(e.target).closest('table');
             $('td input:checkbox', table).attr('checked', e.target.checked);
         });
     });

</script>
Advertisements
This entry was posted in ASP.NET MVC Web Grid, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s