WebGrid Helper with Check all checkboxes

Source: Internet
Author: User

WebGrid Helper with Check all checkboxes

Tuesday, September, 2011asp.net ASP. Html Helper jQuery WebMatrix

Introduction:


WebGrid Helper is one of the helper of the ASP. NET Web Pages (WebMatrix) technology included in ASP. 3. This helper was very easy-to-use and makes it very-simple-to-display tabular data in your Web page. In addition to displaying tabular data, it also supports formatting, paging and sorting features. But WebGrid helper does isn't allow you to put the raw HTML (like checkbox) in the header. In this article, I'll show you how can put HTML element (s) inside the WebGrid helper's header using a simple trick. I'll also show you how can add the Select or unselect all checkboxes feature in your Web page using JQuery and WebGrid Helper.

Description:

          to do it easy-to-add this feature in any of your Web page, I W Ill create a extension method for the WebGrid class. Here is the extension method, 

        public static ihtmlstring Gethtmlwithselectallcheckbox (this WebGrid WebGrid, string tablestyle = Null,string Heade Rstyle = null, string FooterStyle = null, string rowstyle = null,string AlternatingRowStyle = null, String selectedrowstyl E = Null,string caption = NULL, bool Displayheader = true, bool Fillemptyrows = false,string Emptyrowcellvalue = null, IEn umerable<webgridcolumn> columns = null,ienumerable<string> exclusions = NULL, webgridpagermodes mode = Webgridpagermodes.all,string Firsttext = null, string previoustext = null, string nexttext = null,string Lasttext = null, int numericlinkscount = 5, Object htmlattributes = null,string Checkboxvalue = "ID") {var Newco                    Lumn = Webgrid.column (header: "{}", Format:item = new Helperresult (writer = { Writer. Write ("<input class=\" singlecheckbox\ "name=\" selectedrows\ "value=\" + item. Value.gettype (). GetProperty (CHECKboxvalue). GetValue (item. Value, NULL).                ToString () + "\" type=\ "checkbox\"/> ");                })); var newcolumns = columns.                ToList ();                Newcolumns.insert (0, NewColumn);                    var script = @ "<script> if (typeof jQuery = = ' undefined ') { document.write (unescape ("%3cscript src= ' http://ajax.googleapis.c                Om/ajax/libs/jquery/1.6.2/jquery.min.js '%3e%3c/script%3e "));  } (function () {window.settimeout () (function () {initializecheckboxes ();                    }, 1000); function Initializecheckboxes () {$ (function () {$ (' #allCheckBox ').                           Ive (' click ', function () {var isChecked = $ (this). attr (' checked ');                             $ ('. Singlecheckbox '). attr (' checked ', isChecked true:false); $ ('. Singlecheckbox '). Closest (' tr '). addclass (isChecked?                                ' Selected-row ': ' Not-selected-row '); $ ('. Singlecheckbox '). Closest (' tr '). Removeclass (isChecked?                            ' Not-selected-row ': ' Selected-row ');                            });                                $ ('. Singlecheckbox '). Live (' click ', function () {var isChecked = $ (this). attr (' checked '); $ (this). Closest (' tr '). addclass (isChecked?                                ' Selected-row ': ' Not-selected-row '); $ (this). Closest (' tr '). Removeclass (isChecked?                                ' Not-selected-row ': ' Selected-row '); if (isChecked && $ ('. Singlecheckbox '). Length = = $ ('. Selected-row '). Length) $ (' #                                Allcheckbox '). attr (' checked ', true);                         Else           $ (' #allCheckBox '). attr (' checked ', false);                        });                    });            }                })();                </script> "; var html = webgrid.gethtml (TableStyle, HeaderStyle, FooterStyle, RowStyle, Alternat Ingrowstyle, SelectedRowStyle, caption, Displayheader, Fillemptyrows, EMPTYROWCELLV                                        Alue, Newcolumns, exclusions, mode, Firsttext,                                        Previoustext, Nexttext, Lasttext, Numericlinkscount, htmlattributes                ); return Mvchtmlstring.create (HTML. ToString ().            Replace ("{}", "<input type= ' checkbox ' id= ' Allcheckbox '/>") + script); }

          This extension method accepts the same arguments as the Webgrid.gethtml method except that it takes an additional checkboxvalue parameter. This additional parameter are used to set the values of checkboxes. First of all, this method simply inserts an additional column (at position 0) into the existing WebGrid. The header of this column was set to {} and because WebGrid helper always encode the header text. At the end of this method, this text is replaced with a checkbox element.  

In addition to emitting tabular data, this extension method also emit some JavaScript in order to make the Select or U Nselect all checkboxes feature work. This method would add a CSS class Selected-row for rows which is selected and not-selected-row CSS Class For rows which is not selected. You can use these CSS classes to style the selected and unselected rows.

You can use this extension method in ASP. NET MVC, ASP. NET Web Form and ASP. NET Web Pages (Web Matrix), but here I'll only Show you the can leverage this on an ASP. NET MVC 3 application. Here's what's might need to set up a simple Web page,

Person.cs

        public class person        {public            int ID {get; set;}            public string Name {get; set;}            public string Email {get; set;}            public string Adress {get; set;}        }

IPersonService.cs

        Public interface Ipersonservice        {            ilist<person> getpersons ();        }

PersonServiceImp.cs

        public class Personserviceimp:ipersonservice        {public            ilist<person> getpersons ()            {                return _ persons;            }            static ilist<person> _persons = new list<person> ();            Static Personserviceimp ()            {for                (int i =; i < 5020; i++)                    _persons. ADD (new person {ID = i, Name = "person" + I, Adress = "Street," + I, Email = "a" + i + "@a.com"});            }        }

HomeController.cs

        public class Homecontroller:controller        {            private ipersonservice _service;            Public HomeController ()                : This (new Personserviceimp ())            {            } public            HomeController (ipersonservice Service)            {                _service = service;            }            Public ActionResult Index ()            {                return View (_service. Getpersons ());            }            [HttpPost]            Public ActionResult Index (int[] selectedrows)            {                return View (_service. Getpersons ());            }        }

Index.cshtml

        @model ienumerable<webgridhelpercheckallcheckboxes.models.person> @{viewbag.title = "Inde            X ";            Layout = "~/views/shared/_layout.cshtml";        var Grid = new WebGrid (Source:model);  } 

Now just run this application. You'll find the following screen,

Select all or some rows of your table and submit them. You can get all the selected rows of your table as,

Summary:

In ASP 3, you can utilize some helpers of ASP. NET Web Pages (WebMatrix) technology, which can be used for common fu Nctionalities. WebGrid Helper is one of the them. In this article, I showed if you can add the Select or unselect all checkboxes feature in ASP 3 APPL Ication using WebGrid Helper and jQuery. I also showed you can add raw HTML in WebGrid helper ' s header. Hopefully you'll enjoy this article too. A sample application is attached.

WebGrid Helper with Check all checkboxes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.