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. servlet注解@PostConstruct与@PreDestroy

    从Java EE 5规范开始,Servlet中增加了两个影响Servlet生命周期的注解(Annotion):@PostConstruct和@PreDestroy.这两个注解被用来修饰一个非静态的vo ...

  2. HashMap和TreeMap的区别

    HashMap:数组方式存储key/value,线程非安全,允许null作为key和value,key不可以 重复,value允许重复,不保证元素迭代顺序是按照插入时的顺序,key的hash值是先计算 ...

  3. 【bzoj1911】 Apio2010—特别行动队

    http://www.lydsy.com/JudgeOnline/problem.php?id=1911 (题目链接) 题意 给出一个序列,将序列分成连续的几段,每段的价值为a*s*s+b*s+c,其 ...

  4. Jenkins离线下载插件,并安装

     在jenkins点击插件进入wiki,然后点击列表下载一个版本的包 安装是,选择高级的tab,下面就有安装: 还有一种方法,就是装VPN,在高级设置VPN地址.

  5. Android成长日记-使用Intent实现页面跳转

    Intent:可以理解为信使(意图),由Intent来协助完成Android各个组件之间的通讯 Intent实现页面之间的跳转 1->startActivity(intent) 2->st ...

  6. Nginx 日志分享

    Nginx 日志对于大部分人来说是个未被发掘的宝藏,总结之前做某日志分析系统的经验,和大家分享一下 Nginx 日志的纯手工分析方式. Nginx 日志相关配置有 2 个地方:access_log 和 ...

  7. struts2 CVE-2012-0392 S2-008 Strict DMI does not work correctly allows remote command execution and arbitrary file overwrite

    catalog . Description . Effected Scope . Exploit Analysis . Principle Of Vulnerability . Patch Fix 1 ...

  8. 通过Minimal版的iso安装CentOS7之后升级Desktop

    重新安装了CentOS7,但是使用的是Minimal的iso镜像安装的,所以安装之后只有文本界面,这里记录一下重新安装图形界面的过程. 连接网络 通过文本界面登陆后是没有连接网络的,所以需要修改配置连 ...

  9. 获取URL列表,设置代理请求URL,https的加密方式处理

    做了一个测试的一个小工具,需求如下: 1.有一批URL列表,需要知道哪个URL请求响应内容中包含http:关键字的. 2.url请求包括http和https 2种协议 3.要部署在linux服务器上, ...

  10. JSP实现数据传递与保存

    业务逻辑: 1.登陆login.jsp 2.判断登陆是否成功check.jsp 3.登陆成功页面newsDetail.jsp 4.登陆失败转发到login.jsp 代码如下: <%@ page ...