首页 技术 正文
技术 2022年11月8日
0 收藏 376 点赞 1,727 浏览 6124 个字

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.

上一篇: RHEL本地yum源
下一篇: PHP中的NULL类型
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,581
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918