Sunday, April 1, 2012

J query Datatable in asp.net c#, Optimoze Gridview with datatable J query


Controller

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JQueryDataTables.Models;
using JQueryDataTables.Models.Repository;

namespace JQueryDataTables.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// Action that handles initiall request and returns empty view
        /// </summary>
        /// <returns>Home/Index view</returns>
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message:
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table.
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {
            var allCompanies = DataRepository.GetCompanies();
            IEnumerable<Company> filteredCompanies;
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered
                var nameFilter = Convert.ToString(Request["sSearch_1"]);
                var addressFilter = Convert.ToString(Request["sSearch_2"]);
                var townFilter = Convert.ToString(Request["sSearch_3"]);

                //Optionally check whether the columns are searchable at all
                var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isAddressSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                var isTownSearchable = Convert.ToBoolean(Request["bSearchable_3"]);

                filteredCompanies = DataRepository.GetCompanies()
                   .Where(c => isNameSearchable && c.Name.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isAddressSearchable && c.Address.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isTownSearchable && c.Town.ToLower().Contains(param.sSearch.ToLower()));
            }
            else
            {
                filteredCompanies = allCompanies;
            }

            var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isAddressSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isTownSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Company, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.Name :
                                                           sortColumnIndex == 2 && isAddressSortable ? c.Address :
                                                           sortColumnIndex == 3 && isTownSortable ? c.Town :
                                                           "");

            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredCompanies = filteredCompanies.OrderBy(orderingFunction);
            else
                filteredCompanies = filteredCompanies.OrderByDescending(orderingFunction);

            var displayedCompanies = filteredCompanies.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedCompanies select new[] { Convert.ToString(c.ID), c.Name, c.Address, c.Town };
            return Json(new
                            {
                                sEcho = param.sEcho,
                                iTotalRecords = allCompanies.Count(),
                                iTotalDisplayRecords = filteredCompanies.Count(),
                                aaData = result
                            },
                        JsonRequestBehavior.AllowGet);
        }

    }
}
 


Models 


Company.cs


namespace JQueryDataTables.Models
{
    /// <summary>
    /// Company class contains information that shoudl be shown in table
    /// </summary>
    public class Company
    {
        static int nextID = 17;

        public Company()
        {
            ID = nextID++;
        }
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Town { get; set; }
    }

}



JQueryDataTableParamModel.cs




namespace JQueryDataTables.Models
{
    /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>      
        public string sEcho{ get; set; }

        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }

        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }

        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }

        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }

        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }

        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }

    }
}



View


Inde.chtml

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
    <head>
        <title>JQuery DataTables/ASP.NET MVC Integration</title>
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>
    </head>

    <body>
        <div id="container">
            <div id="demo">
                <h2>Index</h2>
                <table id="myDataTable" class="display">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Company name</th>
                            <th>Address</th>
                            <th>Town</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </bod



Use JQueryDataTables.dll library



Dynamically generating thumbnail images in ASP.NET with C#


  <img src="CreateThumbnail.aspx?image=upload/product/<%# Eval("image") %>&width=50" />

 CreateThumbnail.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class CreateThumbnail : System.Web.UI.Page
{
    private void Page_Load(object sender, System.EventArgs e)
    {
        string Image = Request.QueryString["Image"];
        if (Image == null)
        {
            this.ErrorResult();
            return;
        }
        string sSize = Request["Size"];
        int Size = 120;
        if (sSize != null)

            Size = Int32.Parse(sSize);

        string Path = Server.MapPath(Request.ApplicationPath) + "\\" + Image;
        Bitmap bmp = Thumbnail(Path, Size, Size);

        if (bmp == null)
        {
            this.ErrorResult();
            return;
        }
        string OutputFilename = null;
        OutputFilename = Request.QueryString["OutputFilename"];
        if (OutputFilename != null)
        {

            if (this.User.Identity.Name == "")
            {

                bmp.Dispose();
                this.ErrorResult();

            }
            try
            {

                bmp.Save(OutputFilename);

            }

            catch (Exception ex)
            {
                bmp.Dispose();
                this.ErrorResult();
                return;
            }

        }
        Response.ContentType = "image/jpeg";
        bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bmp.Dispose();

    }
    private void ErrorResult()
    {
        Response.Clear();
        Response.StatusCode = 404;
        Response.End();
    }
    public static Bitmap Thumbnail(string lcFilename, int lnWidth, int lnHeight)
    {
        System.Drawing.Bitmap bmpOut = null;
        try
        {
            Bitmap loBMP = new Bitmap(lcFilename);
            ImageFormat loFormat = loBMP.RawFormat;
            decimal lnRatio;
            int lnNewWidth = 0;
            int lnNewHeight = 0;
            if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)

                return loBMP;
            if (loBMP.Width > loBMP.Height)
            {

                lnRatio = (decimal)lnWidth / loBMP.Width;

                lnNewWidth = lnWidth;

                decimal lnTemp = loBMP.Height * lnRatio;

                lnNewHeight = (int)lnTemp;

            }

            else
            {

                lnRatio = (decimal)lnHeight / loBMP.Height;

                lnNewHeight = lnHeight;

                decimal lnTemp = loBMP.Width * lnRatio;

                lnNewWidth = (int)lnTemp;

            }


            bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

            Graphics g = Graphics.FromImage(bmpOut);

            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);

            g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);



            loBMP.Dispose();

        }

        catch
        {

            return null;

        }



        return bmpOut;

    }



}

Product Catelog App class in asp.net c# -7


view_product.aspx

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="view_product.aspx.cs" Inherits="view_product" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <table>
        <tr>
            <td width="63%" align="right" valign="top">
                <table width="90%" border="0" align="right" cellpadding="0" cellspacing="0" style="padding: 40px 0 0 0;
                    margin-top: 10px;">
                    <tr>
                        <td width="90%" align="right" valign="top">
                            <table width="90%" border="0" align="right" cellpadding="0" cellspacing="0" style="margin-bottom: 25px;">
                                <tr>
                                    <td align="left">
                                        <table width="98%" align="left" cellpadding="0" cellspacing="0" style="margin: 25px 0 0 0;">
                                            <tr>
                                                <td align="left" valign="top" class="style13">
                                                    VIEW PRODUCT
                                                </td>
                                                <td width="198" height="35" align="right" valign="middle" class="style4">
                                                </td>
                                            </tr>
                                            </TBODY>
                                        </table>
                                    </td>
                                </tr>
                                <tr>
                                    <td align="left">
                                        <table width="535" border="0" align="center" cellpadding="0" cellspacing="0">
                                            <tr>
                                                <td height="10">
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <table align="center" border="0" cellpadding="0" cellspacing="0" width="535">
                                                        <tr>
                                                            <td height="10">
                                                                <table style="width: 100%">
                                                                    <tr>
                                                                        <td align="left" style="width: 50%">
                                                                            <asp:TextBox ID="txtsearch" Text="Search by ProductName" runat="server" OnClick="this.value = ''; this.style.color = 'black'" OnBlur="javascript:changeText(this.id)"></asp:TextBox>
                                                                            <asp:Button ID="Submit" runat="server" Text="Button" OnClick="Submit_Click" />
                                                                        </td>
                                                                        <td align="right" style="width: 50%">
                                                                            <asp:DropDownList ID="drpcategory" runat="server" OnSelectedIndexChanged="drpcategory_SelectedIndexChanged">
                                                                            </asp:DropDownList>
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td align="left" valign="top" width="520">
                                                                <table border="0" cellpadding="0" cellspacing="0" width="90%">
                                                                    <tr>
                                                                        <td align="center" colspan="3" height="15" valign="middle">
                                                                            <h1>
                                                                                <asp:GridView ID="gvcategory" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                                                                                    CellPadding="5" DataKeyNames="CategoryId" OnPageIndexChanging="gvcategory_PageIndexChanging"
                                                                                    OnRowDeleting="gvcategory_RowDeleting" OnRowEditing="gvcategory_RowEditing" Width="80%">
                                                                                    <HeaderStyle CssClass="Head" />
                                                                                    <RowStyle CssClass="rowtext" />
                                                                                    <Columns>
                                                                                        <asp:TemplateField HeaderText="ID" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="7%">
                                                                                            <ItemTemplate>
                                                                                                <%#Container.DataItemIndex+1 %>
                                                                                            </ItemTemplate>
                                                                                            <ItemStyle HorizontalAlign="Center" Width="7%" />
                                                                                        </asp:TemplateField>
                                                                                        <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" ItemStyle-HorizontalAlign="Left">
                                                                                            <ItemStyle HorizontalAlign="Left" />
                                                                                        </asp:BoundField>
                                                                                        <asp:BoundField DataField="productname" HeaderText="ProductName" ItemStyle-HorizontalAlign="Left">
                                                                                            <ItemStyle HorizontalAlign="Left" />
                                                                                        </asp:BoundField>
                                                                                        <asp:BoundField DataField="productcode" HeaderText="ProductCode" ItemStyle-HorizontalAlign="Left">
                                                                                            <ItemStyle HorizontalAlign="Left" />
                                                                                        </asp:BoundField>
                                                                                        <asp:TemplateField HeaderText="ProductImage">
                                                                                            <ItemTemplate>
                                                                                                <img src="CreateThumbnail.aspx?image=upload/product/<%# Eval("image") %>&width=50" />
                                                                                            </ItemTemplate>
                                                                                        </asp:TemplateField>
                                                                                        <asp:CommandField ControlStyle-CssClass="link" ItemStyle-HorizontalAlign="Center"
                                                                                            ShowEditButton="True">
                                                                                            <ControlStyle CssClass="link" />
                                                                                            <ItemStyle HorizontalAlign="Center" />
                                                                                        </asp:CommandField>
                                                                                        <asp:CommandField ControlStyle-CssClass="link" ItemStyle-HorizontalAlign="Center"
                                                                                            ShowDeleteButton="True">
                                                                                            <ControlStyle CssClass="link" />
                                                                                            <ItemStyle HorizontalAlign="Center" />
                                                                                        </asp:CommandField>
                                                                                    </Columns>
                                                                                </asp:GridView>
                                                                            </h1>
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td align="center" colspan="3" valign="middle">
                                                                            <table border="0" cellpadding="0" cellspacing="0" width="82%">
                                                                                <tr>
                                                                                    <td width="60">
                                                                                        &nbsp;
                                                                                    </td>
                                                                                </tr>
                                                                            </table>
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td align="left" colspan="3" height="60" valign="middle">
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td align="left" valign="middle">
                                                                            &nbsp;
                                                                        </td>
                                                                        <td>
                                                                            &nbsp;
                                                                        </td>
                                                                        <td align="left" valign="middle">
                                                                            <a class="thickbox" style="border: none;">&nbsp;</a>
                                                                        </td>
                                                                    </tr>
                                                                </table>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>
                                                                &nbsp;
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td align="left" valign="top">
                                                                &nbsp;
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td align="left" valign="top">
                                                    &nbsp;
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</asp:Content>







view_product.aspx.cs



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class view_product : System.Web.UI.Page
{
    BALProductMaster bal = new BALProductMaster();
    DALProductMaster dal = new DALProductMaster();
    BALCategoryMaster catbal = new BALCategoryMaster();
    DALCategoryMaster catdal = new DALCategoryMaster();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            drpcategory.DataSource = catdal.SelectCategory();
            drpcategory.DataBind();
            drpcategory.SelectedItem.Text = "category";
            drpcategory.SelectedValue = "id";
            gvbind();
        }
    }
    public void gvbind()
    {
        DataTable dt = dal.Select_ProductMaster();
        gvcategory.DataSource = dt;
        gvcategory.DataBind();
        ViewState["dtpro"] = dt;
    }
    protected void gvcategory_RowEditing(object sender, GridViewEditEventArgs e)
    {
        string productid = gvcategory.DataKeys[e.NewEditIndex].Value.ToString();
        Response.Redirect("Add_product.aspx?id=" + productid);
    }
    protected void gvcategory_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int productid = int.Parse(gvcategory.DataKeys[e.RowIndex].Value.ToString());
        bal.ProductID = productid;
        dal.delete_ProductMaster(bal);
        gvbind();
    }
    protected void gvcategory_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvcategory.PageIndex = e.NewPageIndex;
        gvcategory.DataSource = (DataTable)ViewState["dtpro"];
        gvcategory.DataBind();
    }
    protected void drpcategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        catbal.CategoryId = int.Parse(drpcategory.SelectedValue.ToString());
        DataTable dt = dal.selectR_ProductMasterByCategoryId(catbal);
        gvcategory.DataSource = dt;
        gvcategory.DataBind();
        ViewState["dtpro"] = dt;
    }
    protected void Submit_Click(object sender, EventArgs e)
    {
        string search = txtsearch.Text.ToString();
        DataTable dt = dal.Select_ProductMasterSearch(search);
        gvcategory.DataSource = dt;
        gvcategory.DataBind();
        ViewState["dtcat"] = dt;
    }
}