Use jqgrid--code less in ASP.

Source: Internet
Author: User
Tags jqgrid

This example shows how to generate the front-end Jqgrid code dynamically, typically with only one line of code:

<%=Html.jqGrid<TestModel> (@ "#jqT", "Test", "/home/griddata/")%>

The effect is as follows:

Not only that, using metadata, you automatically bundle different entity objects and automatically generate grids.

If you want to know how to use Jqgrid in ASP. NET MVC, please refer to the

Http://haacked.com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx

Look at the code

1. Extend the HtmlHelper to output a piece of JavaScript to the client.

Code 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 ();
}
}

The above code implies 3 functions to get the sort field, the column headings of the grid, and the Colmodel.

2, to the grid column headings and sorting fields, Colmodel to customize. Take Getcolmodel as an example:

Code 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: ' lef T '},{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. Extend a column width property.

public class Colwidthattribute:attribute
{
Public Colwidthattribute ()
{

}

public int Width {get; set;}
}

4, how to customize the entity object.

Code [DisplayName ("ID")]//temporarily use this to represent sort fields
public class Testmodel
{
[DisplayName ("number")]
[Colwidth (WIDTH=100)]
public int id{get;set;}

[DisplayName ("Support rate")]
[Colwidth (Width = 120)]
public int votes {get; set;}

[DisplayName ("topic")]
[Colwidth (Width = 300)]
public string Title {get; set;}

}

5. The code in the controller.

Code 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", "", "is this a blatant ripoff?"}},
New {id = 3, cell = new[] {"3", "All", "Why is the sky blue?"}}
}
};
Return Json (Jsondata,jsonrequestbehavior.allowget);
}

Be sure to remember to set jsonrequestbehavior.allowget in JSON, otherwise only the table header will have no data in Jqgrid.

6, front-end code.

Code <%@ 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" >
<p>
Put content here.
</p>
<div>

<%=Html.jqGrid<TestModel> (@ "#jqT", "Test", "/home/griddata/")%>
</div>
</asp:Content>

After reading, perhaps you would say this is also called code a little bit less, I just think this article may waste your time.

After reading, perhaps you think this example is too small, also want to be able to automatically support the ability to edit on the Jqgrid, as well as the child table support, and so on ~ ~ ~, I feel very happy.

Use jqgrid--code less in ASP.

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.