Working with Dynamic Pagination in ASP.NET
Pagination is a typical process in data display whereby large sets of data are broken into discrete sections for viewing, more often than not used in conjunction with some type of grid or list component.
CSHTML:
- @using Smp.Web.Common;
- @inherits umbraco.MacroEngines.DynamicNodeContext
- @{
- Smp.Web.WebServices.HistoricalService objHS = new Smp.Web.WebServices.HistoricalService();
- var HS = objHS.GetHistoricalPrices(1, PageSize, "", "");
- var PageCount = 0;
- var PageSize = 10;
- foreach (var item in HS)
- {
- PageCount = item._noOfPages;
- break;
- }
- }
- <div class="historical_content_pop">
- <div class="paginationHolder">
- <ul class="hsPagination paginationList">
- @for (int i = 1; i <= PageCount; i++)
- {
- if (i == 1)
- {
- <li><a pageno="@i" href="javascript:void(0);" class="currentSearchPage">@i</a></li>
- }
- else
- {
- <li><a pageno="@i" href="javascript:void(0);">@i</a></li>
- }
- if (i == 10 && PageCount > 10)
- {
- <li><a class="next" pageno="11" href="javascript:void(0);">
- <img src="/images/pagination_arrow_next.png" alt=">" /></a></li>
- break;
- }
- }
- </ul>
- </div>
- <div class="historicalContcontain">
- <div class="dateFilter">
- <form id="frmHistoricalPrices">
- <input id="txtStartDate" class="priceFilterField firstField" type="text" placeholder="Start Date" />
- <input id="txtEndDate" class="priceFilterField" type="text" placeholder="End Date" />
- <p class="formHelper">Ex: 01/01/2000</p> <a href="javascript:void(0);" id="btnApply"
- class="priceFilterBtn">SEARCH</a>
- </form>
- </div>
- <div class="priceResultHolder">
- <ul class="priceResultHeader">
- <li class="priceDateCol">Date</li>
- <li class="pricePriceCol">Price</li>
- <li class="priceHighCol">High</li>
- <li class="priceVolumeCol">Volume</li>
- </ul>
- @{var count = 1; var classUL = "";}
- @foreach (var item in HS)
- {
- if (count % 2 == 0)
- {
- classUL = "priceResultList alt";
- }
- else
- {
- classUL = "priceResultList";
- }
- count++;
- <ul class="@classUL">
- <li class="priceDateCol">@item._date</li>
- <li class="pricePriceCol">@item._price</li>
- <li class="priceHighCol">@item._high</li>
- <li class="priceVolumeCol">@Convert.ToDecimal(item._volume).ToString("N0")</li>
- </ul>
- }
- </div>
- </div>
- </div>
jQuery:
- <script type="text/javascript">
- $("#btnApply").click(function () {
- FetchHistoricalData(1, 10, this);
- });
- $(".hsPagination li a").die("click").live('click', function () {
- var pageNo = parseInt($(this).attr('pageno'));
- FetchHistoricalData(pageNo, 10, this);
- });
- function FetchHistoricalData(pageNo, pageSize, obj) {
- var startDate = $("#txtStartDate").val();
- var endDate = $("#txtEndDate").val();
- $.ajax({
- type: "POST",
- data: "{pageNo:" + pageNo + ",pageSize:" + pageSize + ",'StDate':'" + startDate + "','EndDate':'" + endDate + "'}",
- url: "/WebServices/HistoricalService.asmx/GetHistoricalPrices",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function (response) {
- var hs = response.d;
- var htmlData = "";
- var htmlPagination = "";
- var classUL = "";
- var pageCount = 0;
- htmlData += "<ul class='priceResultHeader'>";
- htmlData += "<li class='priceDateCol'>Date</li>";
- htmlData += "<li class='pricePriceCol'>Price</li>";
- htmlData += "<li class='priceHighCol'>High</li>";
- htmlData += "<li class='priceVolumeCol'>Volume</li></ul>";
- for (var i = 0; i < hs.length; i++) {
- if (i % 2 == 0) {
- classUL = "priceResultList";
- }
- else {
- classUL = "priceResultList alt";
- }
- htmlData += "<ul class='" + classUL + "'>";
- htmlData += "<li class='priceDateCol'>" + hs[i]._date + "</li>";
- htmlData += "<li class='pricePriceCol'>" + hs[i]._price + "</li>";
- htmlData += "<li class='priceHighCol'>" + hs[i]._high + "</li>";
- htmlData += "<li class='priceVolumeCol'>" + (hs[i]._volume).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + "</li></ul>";
- pageCount = hs[i]._noOfPages;
- }
- $(".priceResultHolder").html(htmlData);
- if ($(obj).hasClass('next')) {
- var prevPage = pageNo - 1;
- var nextPage = pageNo + 10;
- var lastPage = pageNo + 9;
- var last = false;
- if (lastPage > pageCount) {
- lastPage = pageCount;
- last = true;
- }
- htmlPagination += "<li><a pageno='" + prevPage + "' class='prev' href='javascript:void(0);'><img src='/images/pagination_arrow_prev.png' alt='<' /></a></li>";
- for (var i = pageNo; i <= lastPage; i++) {
- if (i == pageNo) {
- htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- else {
- htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- }
- if (!last) {
- htmlPagination += "<li><a pageno='" + nextPage + "' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
- }
- $(".hsPagination").html(htmlPagination);
- htmlPagination = "";
- }
- else if ($(obj).hasClass('prev')) {
- var prevPage = pageNo - 10;
- var nextPage = pageNo + 1;
- var firstPage = pageNo - 9;
- if (pageCount > 10) {
- if (prevPage != 0) {
- htmlPagination += "<li><a pageno='" + prevPage + "' class='prev' href='javascript:void(0);'><img src='/images/pagination_arrow_prev.png' alt='<' /></a></li>";
- }
- for (var i = firstPage; i < nextPage; i++) {
- if (i == nextPage - 1) {
- htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- else {
- htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- }
- htmlPagination += "<li><a pageno='" + nextPage + "' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
- }
- $(".hsPagination").html(htmlPagination);
- htmlPagination = "";
- }
- else if ($(obj).hasClass('priceFilterBtn')) {
- if (pageCount > 1) {
- for (var i = 1; i <= pageCount; i++) {
- if (i == 1) {
- htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- else {
- htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
- }
- if (i == 10 && pageCount > 10) {
- htmlPagination += "<li><a pageno='11' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
- break;
- }
- }
- }
- $(".hsPagination").html(htmlPagination);
- htmlPagination = "";
- }
- else {
- $('.hsPagination li a').each(function () {
- $(this).removeClass('currentSearchPage');
- });
- $(obj).addClass('currentSearchPage');
- }
- htmlData = "";
- }
- });
- }
- </script>
Web Service:
- [WebMethod(EnableSession = true)]
- public List<HistoricalProperty> GetHistoricalPrices(int pageNo, int pageSize, string StDate, string EndDate)
- {
- List<HistoricalProperty> historyPricesList = new List<HistoricalProperty>();
- try
- {
- var skipPrices = (pageNo - 1) * pageSize;
- if (Context.Session["historicalPrice"] != null)
- {
- historyPricesList = (List<HistoricalProperty>)Context.Session["historicalPrice"];
- if (StDate.Trim() != "" || EndDate.Trim() != "")
- {
- historyPricesList = historyPricesList.Where(x => Convert.ToDateTime(x._date) >= Convert.ToDateTime(StDate) && Convert.ToDateTime(x._date) <= Convert.ToDateTime(EndDate)).ToList();
- }
- var totalCount = historyPricesList.Count();
- historyPricesList = historyPricesList.Skip(skipPrices).Take(pageSize).ToList();
- var totalPageCount = 0;
- if (totalCount % pageSize == 0)
- {
- totalPageCount = totalCount / pageSize;
- }
- else
- {
- totalPageCount = totalCount / pageSize + 1;
- }
- foreach (var item in historyPricesList)
- {
- item._totalCount = totalCount;
- item._noOfPages = totalPageCount;
- }
- }
- else
- {
- SMPHistoricalService.Header HisHeader = new SMPHistoricalService.Header();
- HisHeader.Username = ApplicationConstants._HistoricalHeaderUsername;
- SMPHistoricalService.SMPHIstoricalSplice HisSplice = new SMPHistoricalService.SMPHIstoricalSplice();
- HisSplice.HeaderValue = HisHeader;
- SMPHistoricalService.Untitled HisOutputData = HisSplice.SMPXignite_SMPHIstorical(SMPHistoricalService.IdentifierTypes.Symbol, "", "");
- SMPHistoricalService.Quotes[] Quotes = HisOutputData.GetHistoricalQuotesRangeReturnObject.Quotes;
- //This Splice takes the inputs Identifier, IdentifierType, StartDate, EndDate
- //and calls GetHistoricalQuotesRange to generate Untitled.
- var totalCount = Quotes.Count();
- var totalPageCount = 0;
- if (totalCount % pageSize == 0)
- {
- totalPageCount = totalCount / pageSize;
- }
- else
- {
- totalPageCount = totalCount / pageSize + 1;
- }
- foreach (var quote in Quotes)
- {
- historyPricesList.Add(new HistoricalProperty
- {
- _date = quote.Date,
- _price = quote.Price.ToString(),
- _high = quote.High.ToString(),
- _volume = quote.Volume.ToString(),
- _totalCount = totalCount,
- _noOfPages = totalPageCount
- });
- }
- Context.Session["historicalPrice"] = historyPricesList;
- historyPricesList = historyPricesList.Skip(skipPrices).Take(pageSize).ToList();
- }
- }
- catch
- {
- historyPricesList.Add(new HistoricalProperty { _errorMessage = ApplicationConstants._ServiceErrorMessage });
- }
- return historyPricesList;
- }
Working with Cookies in ASP.NET
Usage of Cookies in ASP.NET using C# or jQuery. A cookie is a piece of data which is sent from a website and stored locally by the user’s browser. Cookies are needed because HTTP is stateless. This means that HTTP itself has no way to keep track of a user’s previous activities. One way to create state is by using cookies.
jQuery:
TO STORE:
- $(function() {
- $.cookie("myVar", "Hello World!");
- $.cookie("myVar", { path: '/' }); // Sets the cookie at the root level
- });
TO READ:
- $(function() {
- alert($.cookie("myVar"));
- });
TO DELETE:
- $(function() {
- $.removeCookie("myVar");
- $.removeCookie('myVar', { path: '/' }); // Removes the cookie from the root level
- });
CODE VIEW:
- <!DOCTYPE html>
- <html>
- <head>
- <title>jQuery Session</title>
- <script type='text/javascript' src='jquery-1.9.1.js'></script>
- <script type="text/javascript" src="jquery.cookie.js"></script>
- </head>
- <body>
- <script type='text/javascript'>
- $(window).load(function() {
- // To Store
- $(function() {
- $.cookie("myVar", "Hello World!");
- });
- // To Read
- $(function() {
- alert($.cookie("myVar"));
- });
- });
- </script>
- </body>
- </html>
Working with Session in ASP.NET
Usage of Session in ASP.NET using C# or jQuery. A session is a piece of data which is sent from a website and stored locally by the user’s browser. Sessions are needed because HTTP is stateless. This means that HTTP itself has no way to keep track of a user’s previous activities. One way to create state is by using session.
C# Web Service:
- [WebMethod(EnableSession = true)]
- public List<HistoricalProperty> FetchHistoricalData()
- {
- List<HistoricalProperty> historyList = new List<HistoricalProperty>();
- if (Context.Session["historicalData"] != null)
- {
- historyList = (List<HistoricalProperty>)Context.Session["historicalPrice"];
- ...
- ...
- ...
- }
- else
- {
- ...
- ...
- ...
- Context.Session["historicalData"] = historyList;
- }
- return historyList;
- }
jQuery:
TO STORE:
- $(function() {
- $.session.set("myVar", "Hello World!");
- });
TO READ:
- $(function() {
- alert($.session.get("myVar"));
- });
CODE VIEW:
- <!DOCTYPE html>
- <html>
- <head>
- <title>jQuery Session</title>
- <script type='text/javascript' src='jquery-1.9.1.js'></script>
- <script type="text/javascript" src="jquery.session.js"></script>
- </head>
- <body>
- <script type='text/javascript'>
- $(window).load(function() {
- // To Store
- $(function() {
- $.session.set("myVar", "Hello World!");
- });
- // To Read
- $(function() {
- alert($.session.get("myVar"));
- });
- });
- </script>
- </body>
- </html>
How to upload file using jQuery/Ajax?
The following AJAX File Upload jQuery Tutorial covers how to upload files asynchronously using jQuery Framework.
Generic Handler: AjaxFileUploader.ashx
- public class AjaxFileUploader : IHttpHandler
- {
- public void ProcessRequest(HttpContext context)
- {
- if (context.Request.Files.Count > 0)
- {
- string path = context.Server.MapPath("~/Files");
- if (!Directory.Exists(path))
- Directory.CreateDirectory(path);
- var file = context.Request.Files[0];
- string fileName;
- if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
- {
- string[] files = file.FileName.Split(new char[] { '\\' });
- fileName = files[files.Length - 1];
- }
- else
- {
- fileName = file.FileName;
- }
- string strFileName = fileName;
- fileName = Path.Combine(path, fileName);
- file.SaveAs(fileName);
- string msg = "{";
- msg += string.Format("error:'{0}',\n", string.Empty);
- msg += string.Format("msg:'{0}',\n", strFileName);
- msg += string.Format("path:'{0}'", path.Replace("\\", "?"));
- msg += "}";
- context.Response.Write(msg);
- }
- }
- public bool IsReusable
- {
- get
- {
- return true;
- }
- }
- }
HTML:
- <div class="resumeUpload">
- <input type="file" id="fileToUpload" name="fileToUpload" onchange="ajaxFileUpload();" />
- <div class="fileBtn">
- <span>File</span>
- <input id="fileUploadBox" disabled="disabled" value="@GetDictionary("No files selected")" />
- </div>
- </div>
jQuery:
- <script type="text/javascript">
- function ajaxFileUpload() {
- $("#fileToUpload").ajaxStart(function () {
- $('#fileUploadBox').val('Uploading...');
- $('#fileUploadBox').addClass('loadinggif');
- }).ajaxComplete(function () {
- $('#fileUploadBox').removeClass('loadinggif');
- });
- $.ajaxFileUpload({
- url: '/GenericHandlers/AjaxFileUploader.ashx',
- secureuri: false,
- fileElementId: 'fileToUpload',
- dataType: 'json',
- data: { name: 'logan', id: 'id' },
- success: function (data, status) {
- if (typeof (data.error) != 'undefined') {
- if (data.error != '') {
- //alert(data.error);
- } else {
- $('#fileUploadBox').val(data.msg);
- $("#hdnFilePath").val(data.path + "?" + data.msg);
- }
- }
- },
- error: function (data, status, e) {
- //alert(e);
- $('#fileUploadBox').val('File size is too large.');
- }
- });
- $.extend({
- handleError: function (s, xhr, status, e) {
- if (s.error)
- s.error(xhr, status, e);
- else if (xhr.responseText)
- console.log(xhr.responseText);
- }
- });
- return false;
- }
- </script>
How to Remove the white spaces at the start and end of the string?
The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>jQuery.trim demo</title>
- <script src="//code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
- <pre id="original"></pre>
- <pre id="trimmed"></pre>
- <script>
- var str = " lots of spaces before and after ";
- $( "#original" ).html( "Original String: '" + str +"'");
- $( "#trimmed" ).html( "Trimmed String: '" + $.trim(str) +"'");
- </script>
- </body>
- </html>
How to Limit the number of characters allowed in form input text field?
By using the following attribute we can easily limit the number of characters allowed in form input text field.
maxlength="10"Adding this attribute to your control:
<input type="text"
id="txtPhone"
name="Phone"
maxlength="10" />
How to get the Created & last Published date of a Node in Umbraco?
Using the following CSHTML code we can easily get the Created & last Published date of a Node in Umbraco.
To get the Created Date of an Umbraco Node:
To get the Created Date of an Umbraco Node:
- @Model.CreateDate
- @Model.UpdateDate