WebGrid Helper with Check All Checkboxes

myEvernote Link

Tuesday, September 13, 2011ASP.NET ASP.NET MVC Html Helper jQuery WebMatrix

Introduction:


          WebGrid helper is one of the helper of ASP.NET Web Pages(WebMatrix) technology included in ASP.NET MVC 3. This helper is 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 not allow you to put raw html(like checkbox) in the header. In this article, I will show you how you can put html element(s) inside the WebGrid helper's header using a simple trick. I will also show you how you can add the select or unselect all checkboxes feature in your web page using jQuery and WebGrid helper.  

Description:

To make it easy to add this feature in any of your web page, I will create an extension method for the WebGrid class. Here is the extension method, 

        public static IHtmlString GetHtmlWithSelectAllCheckBox(this WebGrid webGrid, string tableStyle = null,
string headerStyle = null, string footerStyle = null, string rowStyle = null,
string alternatingRowStyle = null, string selectedRowStyle = null,
string caption = null, bool displayHeader = true, bool fillEmptyRows = false,
string emptyRowCellValue = null, IEnumerable<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 newColumn = 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.com/ajax/libs/jquery/1.6.2/jquery.min.js'%3E%3C/script%3E""
)
);
} (function(){ window.setTimeout(function() { initializeCheckBoxes(); }, 1000);
function initializeCheckBoxes(){ $(function () { $('#allCheckBox').live('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,
alternatingRowStyle, selectedRowStyle, caption,
displayHeader, fillEmptyRows, emptyRowCellValue,
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 additionalcheckBoxValue parameter. This additional parameter is used to set the values of checkboxes. First of all, this method simply insert an additional column(at position 0) into the existing WebGrid. The header of this column is set to {}, 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 unselect all checkboxes feature work. This method will add a css class selected-row for rows which are selected and not-selected-row css class for rows which are 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 will only show you how you can leverage this in an ASP.NET MVC 3 application. Here is what you 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 = 5000; 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 = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
var grid = new WebGrid(source: Model);
}
<h2>Index</h2> <style>
.selected-row{
background: none repeat scroll 0 0 #CACAFF;
color: #222222;
}
.not-selected-row{
background: none repeat scroll 0 0 #FFFFFF;
color: #000000;
}
.grid
{
border-collapse: collapse;
}
.grid th,td
{
padding : 10px;
border: 1px solid #000;
}
</style> @using (Html.BeginForm())
{
<fieldset>
<legend>Person</legend>
@grid.GetHtmlWithSelectAllCheckBox(
tableStyle: "grid", checkBoxValue: "ID",
columns: grid.Columns(
grid.Column(columnName: "Name"),
grid.Column(columnName: "Email"),
grid.Column(columnName: "Adress")
))
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}

Now just run this application. You will 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.NET MVC 3, you can utilize some helpers of ASP.NET Web Pages(WebMatrix) technology, which can be used for common functionalities. WebGrid helper is one of them. In this article, I showed you how you can add the select or unselect all checkboxes feature in ASP.NET MVC 3 application using WebGrid helper and jQuery. I also showed you how you can add raw html in WebGrid helper's header. Hopefully you will enjoy this article too. A sample application is attached.

WebGrid Helper with Check All Checkboxes的更多相关文章

  1. WebGrid with filtering, paging and sorting 【转】

    WebGrid with filtering, paging and sorting by Jose M. Aguilar on April 24, 2012 in Web Development A ...

  2. Web Pages - Efficient Paging Without The WebGrid

    Web Pages - Efficient Paging Without The WebGrid If you want to display your data over a number of p ...

  3. ASP.NET Web Pages:WebGrid 帮助器

    ylbtech-.Net-ASP.NET Web Pages:WebGrid 帮助器 1.返回顶部 1. ASP.NET Web Pages - WebGrid 帮助器 WebGrid - 众多有用的 ...

  4. [Transducer] Make an Into Helper to Remove Boilerplate and Simplify our Transduce API

    Our transduce function is powerful but requires a lot of boilerplate. It would be nice if we had a w ...

  5. RazorExtensions Templated Razor Delegates

    原文发布时间为:2011-04-27 -- 来源于本人的百度文章 [由搬家工具导入] Templated Razor Delegates David Fowler turned me on to a ...

  6. .NET软件工程师面试总结

    1.手写画出系统架构图,系统代码架构,有什么技术难点?  2.手写画出系统部署图 CDN(一般购买别人的服务器会自动CDN,他们自己配置就OK啦) 3.asp.net 的session怎么实现会话共享 ...

  7. Report List Controls

    Report风格的ListCtrl的扩展,原文链接地址:http://www.codeproject.com/Articles/5560/Another-Report-List-Control 1.列 ...

  8. 补习系列(12)-springboot 与邮件发送

    目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...

  9. 期货大赛项目|六,iCheck漂亮的复选框

    废话不多说,直接上图 对,还是上篇文章的图,这次我们不研究datatables,而是看这个复选框,比平常的复选框漂亮太多 看看我是如何实现的吧 插件叫iCheck 用法也简单 引入js和css $(& ...

随机推荐

  1. mac下搭建java开发环境:eclipse+tomcat+maven

    一.安装eclipse 直接下载 二.安装JDK 下载mac版专用的jdk1.7,地址如下:http://jdk7.java.net/macportpreview/, 确认java使用的版本:开一个终 ...

  2. VS2015 安装mvc4安装包以及vs2010 sp1后导致Razor语法失效代码不高亮(能正常运行)/视图页面无法智能提示(.cshtml)解决办法

    VS2015默认asp.net mvc 版本为5.0以上,默认不支持创建5.0以下的版本.所以想要使用mvc 4.0只能单独安装.在网上搜了几篇教程后在微软官网下载了Visual Studio 201 ...

  3. Linux网卡的相关配置总结

    当有多个网卡的时候,我们需要进行相关的配置. 一.如何改变网卡的名字? 修改/etc/udev/rules.d/70-persistent-net.rules 进去之后的效果是 根据mac地址,把没用 ...

  4. java高新技术-类加载器

    1.类加载器及委托机制的深入分析 > 类加载器的作用:一个java文件中的出现的类,首先要把这个类的字节码加载到内存中,这个类的信息放在硬盘的classPath下的class文件中,  把cla ...

  5. Android程序设计-圆形图片的实现

    在android中,google只提供了对图形的圆形操作,而没有实现对图片的圆形操作,所以我们无法实现上述操作,在此我们将使用框架进行设计(下述框架为as编写): https://github.com ...

  6. Android成长日记-使用GridView显示多行数据

    本节将实现以下效果 Ps:看起来很不错的样子吧,而且很像九宫格/se ----------------------------------------------------------------- ...

  7. 《ODAY安全:软件漏洞分析技术》学习心得-----shellcode的一点小小的思考

    I will Make Impossible To I'm possible -----------LittleHann 看了2个多星期.终于把0DAY这本书给看完了,自己动手将书上的实验一个一个实现 ...

  8. iOS 解决一个因三方静态库冲突产生的duplicate symbol的问题

    最近在开发项目时编译三方.a时出现了冲突,原因是存在duplicate symbol. <1>模拟器编译时,应用的即时通讯模块采用的三方库(容联云),和视频监控模块采用的三方库(海康威视) ...

  9. 数据结构2 静态区间第K大/第K小

    给定数组$A[1...N]$, 区间$[L,R]$中第$K$大/小的数的指将$A[L...R]$中的数从大到小/从小到大排序后的第$K$个. "静态"指的是不带修改. 这个问题有多 ...

  10. Python基本数据类型之int

    一.int的范围 2.7: 32位:-2^31~2^31-1 64位:-2^63~2^63-1 3.5: 在3.5中init长度理论上是无限的 二.python内存机制 在一般情况下当变量被赋值后,内 ...