Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

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



Friday, February 3, 2012

ASP.NET AJAX UpdateProgress Control

In head Section

<script language="javascript" type="text/javascript">

   var prm = Sys.WebForms.PageRequestManager.getInstance();
   prm.add_initializeRequest(InitializeRequest);
   prm.add_endRequest(EndRequest);
   var postBackElement;
   function InitializeRequest(sender, args)
   {

      if (prm.get_isInAsyncPostBack())
         args.set_cancel(true);
      postBackElement = args.get_postBackElement();
      if (postBackElement.id == 'Button1')
         $get('UpdateProgress1').style.display = 'block';
   }
 
   function EndRequest(sender, args)
   {
       if (postBackElement.id == 'Button1')
          $get('UpdateProgress1').style.display = 'none';
   }

</script>

 In Body Section

<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;
    </div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Width="145px"></asp:Label>
            </ContentTemplate>
         <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click"/>
        </Triggers>
        </asp:UpdatePanel>
       <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="0" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <script type="text/javascript">document.write("<div class='UpdateProgressBackground'></div>");</script>
                <center><div class="UpdateProgressContent">Loading...</div></center>
            </ProgressTemplate>
        </asp:UpdateProgress>

        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </form>
</body>

Tuesday, March 29, 2011

ASP.NET AJAX Control Toolkit

Welcome to the ASP.NET AJAX Control Toolkit.

Choose from any of the samples on the left to see the live controls in action, and experiment with their different possibilities.
What is the ASP.NET AJAX Control Toolkit?
The ASP.NET AJAX Control Toolkit is an open-source project built on top of the Microsoft ASP.NET AJAX framework. It is a joint effort between Microsoft and the ASP.NET AJAX community that provides a powerful infrastructure to write reusable, customizable and extensible ASP.NET AJAX extenders and controls, as well as a rich array of controls that can be used out of the box to create an interactive Web experience.

The AJAX Control Toolkit contains more than 30 controls that enable you to easily create rich, interactive web pages.

To get started, and to install the Ajax Control Toolkit, visit the AJAX Control Toolkit Project Page on CodePlex.

To learn more, read the Getting Started Tutorial, or the other walkthroughs, tutorials and videos shown on the left

Friday, December 10, 2010

Consuming webservices

http://www.asp.net/ajax/documentation/live/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

Saturday, December 4, 2010

Download Latest Version of AJAX Control Toolkit Version 3.0

Download Latest Version of AJAX Control Toolkit Version 3.0

Latest version of AJAX Control Toolkit V 3.0 includes

New controls
This release includes three important new controls:
  • HTMLEditor
    The HTMLEditor control allows you to easily create and edit HTML content. You can edit in design mode, as a rich text editor, or in source view to edit the HTML markup directly.

  • ComboBox
    The ComboBox control provides a DropDownList of items, combined with TextBox. Different modes determine the interplay between the text entry and the list of items.
    Many thanks to Dan Ludwig for building this.

  • ColorPicker
    The ColorPicker Control Extender can be attached to any ASP.NET TextBox control. It provides client-side color-picking functionality with UI in a popup control.
    Many thanks to Alexander Turlov for building this.

Thursday, March 11, 2010

HOW TO Instantiate Controls Imperatively in Ajax

.aspx page


<head> 
     <title>Simple Watermark</title> 
      
 
     <script type="text/javascript"> 
  
        Sys.require(Sys.components.watermark, function() { 
 
           Sys.create.watermark("#input1", "Enter something..."); 

        }); 
      
     </script> 
 </head> 
 <body> 
  
     <input id="input1" /> 
  
</body> 
</html> 
the Sys.require() method is used to load all of the scripts required by the Watermark control

AJAX with Continuous Progress Bar


AJAX with Continuous Progress Bar
Progress Bar to work in ASP.Net.
I have my Button, the ModalPopupExtender, the Panel that the extender will display, the Script Manager, and a hidden control.

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <div>
            <asp:Button ID="btnSubmit" onclick="btnSubmit_Click" OnClientClick="StartProgressBar()"
                     runat="server" Text="Submit Time" Width="170px" />

            <ajaxToolkit:ModalPopupExtender ID="ProgressBarModalPopupExtender" runat="server"
                     BackgroundCssClass="ModalBackground" behaviorID="ProgressBarModalPopupExtender"
                     TargetControlID="hiddenField" PopupControlID="Panel1" />

            <asp:Panel ID="Panel1" runat="server" Style="display: none; background-color: #C0C0C0;">
                 <img src="progressbar.gif" alt="" />
            </asp:Panel>

            <asp:HiddenField ID="hiddenField" runat="server" />
       </div>
   </ContentTemplate>
</asp:UpdatePanel>

Also notice that the Button has both of the click events populated. The onclick event will be the server-side event handler.

protected void btnSubmit_Click(object sender, EventArgs e)
{
     Thread.Sleep(7000);
     ProgressBarModalPopupExtender.Hide();
}

The OnClientClick event will be calling a javascript function..

<script language="javascript" type="text/javascript">
        function StartProgressBar() {
                var myExtender = $find('ProgressBarModalPopupExtender');
                myExtender.show();
                return true;
        }
</script>

ModalPopupExtender.

Add link to your Head tag

<link href="main.css" rel="stylesheet" type="text/css" />

Then add this entry to the CSS file.

.ModalBackground
{
        background-color:Gray;

        filter:alpha(opacity=50);
        -moz-opacity:0.5;
        -khtml-opacity: 0.5;
        opacity: 0.5;
}

Tuesday, January 26, 2010

Get the value from tabel in three drop down on select index change Event

string strCategory1 = “select categoryname,categoryid from tbl_test where status=’Active’”;
SqlCommand cmdCategory1 = new SqlCommand(strCategory1, conn);
cmdCategory1.CommandType = CommandType.Text;
SqlDataAdapter daCategory1 = new SqlDataAdapter(cmdCategory1);
DataSet dsCategory1 = new DataSet();
daCategory1.Fill(dsCategory1, “tbl_maincategory”);
drpmaincategory.DataSource = dsCategory1.Tables["tbl_test"];
drpmaincategory.DataTextField = “categoryname”;
drpmaincategory.DataValueField = “categoryid”;
drpmaincategory.DataBind();
SqlCommand mySqlSelect = new SqlCommand(“Select * from tbl_list where id= ‘” + Request.Params.Get(“id”) + “‘”, conn);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataSet dt1 = new DataSet();
mySqlAdapter.Fill(dt1);
DataTable dtr1 = dt1.Tables[0];
string m = dt1.Tables[0].Rows[0]["categoryid"].ToString();
drpmaincategory.SelectedValue = m;
drpmaincategory_SelectedIndexChanged(sender, e);
drpsubcategory.SelectedValue = dt1.Tables[0].Rows[0]["subcategoryid"].ToString();
string strCategory3 = “select * from tbl_category where status=’Active’ and id=’” + drpmaincategory.SelectedValue.ToString() + “‘”;
SqlCommand cmdCategory3 = new SqlCommand(strCategory3, conn);
cmdCategory3.CommandType = CommandType.Text;
SqlDataAdapter daCategory3 = new SqlDataAdapter(cmdCategory3);
DataSet dsCategory3 = new DataSet();
daCategory3.Fill(dsCategory3, “tbl_subcategory”);
drpsubcategory.DataSource = dsCategory1.Tables["tbl_category"];
drpsubcategory.DataTextField = “subcategoryname”;
drpsubcategory.DataValueField = “subcategoryid”;

Monday, January 25, 2010

Use of three dropdown in Ajax

<asp:UpdatePanel id=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional”>
<contenttemplate>
<asp:DropDownList width=”250px”  id=”drpmaincategory” runat=”server” OnSelectedIndexChanged=”drpmaincategory_SelectedIndexChanged” AutoPostBack=”true” >
</asp:DropDownList>  <asp:RequiredFieldValidator ID=”RequiredFieldValidator3″ runat=”server”
ControlToValidate=”drpmaincategory” ErrorMessage=”Please Select Category” Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblmaincategory” runat=”server” Text=”"></asp:Label></TD>
<asp:DropDownList id=”drpsubcategory” width=”250px” runat=”server” OnSelectedIndexChanged=”drpsubcategory_SelectedIndexChanged1″ AutoPostBack=”true” CssClass=”textfield”>
</asp:DropDownList> <asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server”
ControlToValidate=”drpsubcategory” ErrorMessage=”Please Select Subcategory”
Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblsubcategory” runat=”server” Text=”"></asp:Label></TD>
<asp:DropDownList id=”drpproductname” width=”250px” runat=”server”>
</asp:DropDownList><asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server”
ControlToValidate=”drpproductname” ErrorMessage=”Please Select Product”
Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblproduct” runat=”server” Text=”"></asp:Label></TD>
</contenttemplate>
<triggers>
<asp:AsyncPostBackTrigger ControlID=”drpmaincategory” EventName=”SelectedIndexChanged” />
<asp:AsyncPostBackTrigger ControlID=”drpsubcategory” EventName=”SelectedIndexChanged” />
</triggers>
</asp:UpdatePanel>




Code Behind the Ajax Control

f (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
Next, we create the Tick handler, which will retrieve the current time from the HiddenField, add one second to it, and display it in the Literal field, then it will save the new value to the HiddenField to be used again in a second:
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
Because AJAX is native to ASP.NET 3.5, we do not need to add anything extra or reference any other namespaces. All we simply need to do is include the ScriptManager and UpdatePanel controls, ASP.NET takes care of everything else for you behind the scenes.
If we run this now the timer will begin counting up as soon as the page is loaded. It is already fully-functional. But to test it, let’s add a textbox and a button so that we can postback the page and demonstrate how to keep the timer counting up regardless.

Finally, we add the logic to the code-behind that will handle the button click event:
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
Now when we run this, you will see that we’re able to submit our name without the timer stopping or pausing or restarting.
Our ASPX page looks like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
}