在Asp.net MVC使用jqGrid--代码少点再少点
本示例显示了如何动态生成前端jqGrid代码,一般情况仅一行代码:
<%=Html.jqGrid<TestModel>(@"#jqT", "Test", "/Home/GridData/")%>
效果如下:
还不仅仅如此,利用MetaData,将自动对不同实体对象进行捆绑,自动生成Grid。
如果你想知道如何在asp.net MVC中使用jqGrid,请参考
http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx
看代码
1、 扩展HtmlHelper来输出一段Javascript到客户端。
代码
public static class jqGridExtensions
{
public static string jqGrid<T>(this HtmlHelper helper, string gridID, string caption, string url)
{
if (gridID.Substring(0, 1) != "#")
gridID = "#" + gridID;
string pagerID = string.Format("{0}_pager", gridID);
StringBuilder sb = new StringBuilder();
sb.AppendLine(" <script type=\"text/javascript\">$(function(){");//jQuery(document).ready(function() {
sb.AppendLine("$('%%GRIDID%%').jqGrid({".Replace("%%GRIDID%%", gridID)); //jQuery("#list").jqGrid({
sb.AppendFormat("url:'{0}',", url); // url: '/Home/GridData/',
sb.Append("datatype: 'json',mtype: 'GET',"); // datatype: 'json',mtype: 'GET',
sb.AppendFormat("colNames:[{0}],", GetColNames<T>());
sb.AppendFormat("colModel:[{0}],", GetColModel<T>());
sb.Append("pager: '%%GRIDPAGERID%%',rowNum: 20,rowList: [10, 20, 50,100],".Replace("%%GRIDPAGERID%%", pagerID));
sb.AppendFormat("sortname:'{0}',sortorder: 'desc',", GetSortField<T>());
sb.Append("viewrecords: true,imgpath: '/themes/redmond/images',");
sb.AppendFormat("caption: '{0}'", caption);
sb.Append("});\n$('%%GRIDID%%').jqGrid('navGrid','%%GRIDPAGERID%%',{ edit: false, add: false, del: false });".Replace("%%GRIDID%%", gridID).Replace("%%GRIDPAGERID%%", pagerID));
sb.Append("});</script>\n");
sb.AppendFormat("<table id=\"{0}\" class=\"scroll\" cellpadding=\"0\" cellspacing=\"0\"></table>", gridID.Substring(1));
sb.AppendFormat("<div id=\"{0}\" class=\"scroll\" style=\"text-align:center;\"></div>", pagerID.Substring(1));
sb.AppendLine();
return sb.ToString();
}
}
{
public static string jqGrid<T>(this HtmlHelper helper, string gridID, string caption, string url)
{
if (gridID.Substring(0, 1) != "#")
gridID = "#" + gridID;
string pagerID = string.Format("{0}_pager", gridID);
StringBuilder sb = new StringBuilder();
sb.AppendLine(" <script type=\"text/javascript\">$(function(){");//jQuery(document).ready(function() {
sb.AppendLine("$('%%GRIDID%%').jqGrid({".Replace("%%GRIDID%%", gridID)); //jQuery("#list").jqGrid({
sb.AppendFormat("url:'{0}',", url); // url: '/Home/GridData/',
sb.Append("datatype: 'json',mtype: 'GET',"); // datatype: 'json',mtype: 'GET',
sb.AppendFormat("colNames:[{0}],", GetColNames<T>());
sb.AppendFormat("colModel:[{0}],", GetColModel<T>());
sb.Append("pager: '%%GRIDPAGERID%%',rowNum: 20,rowList: [10, 20, 50,100],".Replace("%%GRIDPAGERID%%", pagerID));
sb.AppendFormat("sortname:'{0}',sortorder: 'desc',", GetSortField<T>());
sb.Append("viewrecords: true,imgpath: '/themes/redmond/images',");
sb.AppendFormat("caption: '{0}'", caption);
sb.Append("});\n$('%%GRIDID%%').jqGrid('navGrid','%%GRIDPAGERID%%',{ edit: false, add: false, del: false });".Replace("%%GRIDID%%", gridID).Replace("%%GRIDPAGERID%%", pagerID));
sb.Append("});</script>\n");
sb.AppendFormat("<table id=\"{0}\" class=\"scroll\" cellpadding=\"0\" cellspacing=\"0\"></table>", gridID.Substring(1));
sb.AppendFormat("<div id=\"{0}\" class=\"scroll\" style=\"text-align:center;\"></div>", pagerID.Substring(1));
sb.AppendLine();
return sb.ToString();
}
}
上述代码隐含了3个函数来取得排序字段,Grid的列标题及ColModel。
2、 对Grid的列标题及排序字段,ColModel进行定制。以GetColModel为例:
代码
private static string GetColModel<T>()
{
ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
StringBuilder sb = new StringBuilder();
int width=100;
foreach (ModelMetadata proMeta in metadata.Properties)
{
ColWidthAttribute colWidthAttr = GetCustomAttribute<ColWidthAttribute>(proMeta) as ColWidthAttribute;
if (colWidthAttr != null)
width = colWidthAttr.Width;
sb.Append("{");
sb.AppendFormat("name:'{0}',index:'{0}',width:{1},align:'left'", proMeta.PropertyName, width);
sb.Append("},");
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
//return "{ name: 'Id', index: 'Id', width: 140, align: 'left' }, { name: 'Votes', index: 'Votes', width: 180, align: 'left' },{ name: 'Title', index: 'Title', width: 400, align: 'left',editable:true}";
}
private static object GetCustomAttribute<T>(ModelMetadata proMeta)
{
PropertyInfo property = proMeta.ContainerType.GetProperty(proMeta.PropertyName);
object[] propertyAttributes = property.GetCustomAttributes(typeof(T), true);
if (propertyAttributes.Length > 0)
{
return (propertyAttributes[0]);
}
return null;
}
{
ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
StringBuilder sb = new StringBuilder();
int width=100;
foreach (ModelMetadata proMeta in metadata.Properties)
{
ColWidthAttribute colWidthAttr = GetCustomAttribute<ColWidthAttribute>(proMeta) as ColWidthAttribute;
if (colWidthAttr != null)
width = colWidthAttr.Width;
sb.Append("{");
sb.AppendFormat("name:'{0}',index:'{0}',width:{1},align:'left'", proMeta.PropertyName, width);
sb.Append("},");
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
//return "{ name: 'Id', index: 'Id', width: 140, align: 'left' }, { name: 'Votes', index: 'Votes', width: 180, align: 'left' },{ name: 'Title', index: 'Title', width: 400, align: 'left',editable:true}";
}
private static object GetCustomAttribute<T>(ModelMetadata proMeta)
{
PropertyInfo property = proMeta.ContainerType.GetProperty(proMeta.PropertyName);
object[] propertyAttributes = property.GetCustomAttributes(typeof(T), true);
if (propertyAttributes.Length > 0)
{
return (propertyAttributes[0]);
}
return null;
}
3、 扩展一个列宽(Column Width)属性。
public class ColWidthAttribute: Attribute
{
public ColWidthAttribute()
{
}
public int Width { get; set; }
}
{
public ColWidthAttribute()
{
}
public int Width { get; set; }
}
4、 如何定制实体对象。
代码
[DisplayName("ID")]//暂时用这个来表示排序字段
public class TestModel
{
[DisplayName("编号")]
[ColWidth(Width=100)]
public int ID{get;set;}
[DisplayName("支持率")]
[ColWidth(Width = 120)]
public int Votes { get; set; }
[DisplayName("议题")]
[ColWidth(Width = 300)]
public string Title { get; set; }
}
public class TestModel
{
[DisplayName("编号")]
[ColWidth(Width=100)]
public int ID{get;set;}
[DisplayName("支持率")]
[ColWidth(Width = 120)]
public int Votes { get; set; }
[DisplayName("议题")]
[ColWidth(Width = 300)]
public string Title { get; set; }
}
5、 Controller中的代码。
代码
public ActionResult GridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 1, // we'll implement later
page = page,
records = 3, // implement later
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
{
var jsonData = new
{
total = 1, // we'll implement later
page = page,
records = 3, // implement later
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
千万要记得JSon中设置JsonRequestBehavior.AllowGet,否则jqGrid中将只有表头没有数据。
6、 前端代码。
代码
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
About Us
</asp:Content>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
Put content here.
</p>
<div>
<%=Html.jqGrid<TestModel>(@"#jqT", "Test", "/Home/GridData/")%>
</div>
</asp:Content>
<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
About Us
</asp:Content>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
Put content here.
</p>
<div>
<%=Html.jqGrid<TestModel>(@"#jqT", "Test", "/Home/GridData/")%>
</div>
</asp:Content>
看完,也许你会说这还叫代码少一点,我只是觉得这篇文章可能浪费你的时间。
看完,也许你觉得这个例子威力太小,还想要能够自动支持在jqGrid上是否能够编辑,以及子表支持,等等~~~,我就觉得很欣慰了。