Archive for January 2014

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:

  1. @using Smp.Web.Common;
  2. @inherits umbraco.MacroEngines.DynamicNodeContext
  3. @{
  4.     Smp.Web.WebServices.HistoricalService objHS = new Smp.Web.WebServices.HistoricalService();
  5.     var HS = objHS.GetHistoricalPrices(1, PageSize, "", "");
  6.     var PageCount = 0;
  7.     var PageSize = 10;
  8.     foreach (var item in HS)
  9.     {
  10.         PageCount = item._noOfPages;
  11.         break;
  12.     }
  13. }
  14. <div class="historical_content_pop">
  15.     <div class="paginationHolder">
  16.     <ul class="hsPagination paginationList">
  17.     @for (int i = 1; i <= PageCount; i++)
  18.     {
  19.         if (i == 1)
  20.         {
  21.         <li><a pageno="@i" href="javascript:void(0);" class="currentSearchPage">@i</a></li>
  22.         }
  23.         else
  24.         {
  25.         <li><a pageno="@i" href="javascript:void(0);">@i</a></li>
  26.         }
  27.         if (i == 10 && PageCount > 10)
  28.         {
  29.         <li><a class="next" pageno="11" href="javascript:void(0);">
  30.             <img src="/images/pagination_arrow_next.png" alt=">" /></a></li>
  31.             break;
  32.         }
  33.     }
  34.     </ul>
  35.     </div>
  36.     <div class="historicalContcontain">
  37.         <div class="dateFilter">
  38.             <form id="frmHistoricalPrices">
  39.             <input id="txtStartDate" class="priceFilterField firstField" type="text" placeholder="Start Date" />
  40.             <input id="txtEndDate" class="priceFilterField" type="text" placeholder="End Date" />
  41.             <p class="formHelper">Ex: 01/01/2000</p> <a href="javascript:void(0);" id="btnApply"
  42.                 class="priceFilterBtn">SEARCH</a>
  43.             </form>
  44.         </div>
  45.         <div class="priceResultHolder">
  46.             <ul class="priceResultHeader">
  47.                 <li class="priceDateCol">Date</li>
  48.                 <li class="pricePriceCol">Price</li>
  49.                 <li class="priceHighCol">High</li>
  50.                 <li class="priceVolumeCol">Volume</li>
  51.             </ul>
  52.             @{var count = 1; var classUL = "";}
  53.             @foreach (var item in HS)
  54.             {
  55.                 if (count % 2 == 0)
  56.                 {
  57.                     classUL = "priceResultList alt";
  58.                 }
  59.                 else
  60.                 {
  61.                     classUL = "priceResultList";
  62.                 }
  63.                 count++;
  64.                 <ul class="@classUL">
  65.                     <li class="priceDateCol">@item._date</li>
  66.                     <li class="pricePriceCol">@item._price</li>
  67.                     <li class="priceHighCol">@item._high</li>
  68.                     <li class="priceVolumeCol">@Convert.ToDecimal(item._volume).ToString("N0")</li>
  69.                 </ul>
  70.             }
  71.         </div>
  72.     </div>
  73. </div>

jQuery:

  1. <script type="text/javascript">
  2. $("#btnApply").click(function () {
  3.     FetchHistoricalData(1, 10, this);
  4. });
  5. $(".hsPagination li a").die("click").live('click', function () {
  6.     var pageNo = parseInt($(this).attr('pageno'));
  7.     FetchHistoricalData(pageNo, 10, this);
  8. });
  9. function FetchHistoricalData(pageNo, pageSize, obj) {
  10.     var startDate = $("#txtStartDate").val();
  11.     var endDate = $("#txtEndDate").val();
  12.     $.ajax({
  13.         type: "POST",
  14.         data: "{pageNo:" + pageNo + ",pageSize:" + pageSize + ",'StDate':'" + startDate + "','EndDate':'" + endDate + "'}",
  15.         url: "/WebServices/HistoricalService.asmx/GetHistoricalPrices",
  16.         contentType: "application/json; charset=utf-8",
  17.         dataType: "json",
  18.         success: function (response) {
  19.             var hs = response.d;
  20.             var htmlData = "";
  21.             var htmlPagination = "";
  22.             var classUL = "";
  23.             var pageCount = 0;
  24.             htmlData += "<ul class='priceResultHeader'>";
  25.             htmlData += "<li class='priceDateCol'>Date</li>";
  26.             htmlData += "<li class='pricePriceCol'>Price</li>";
  27.             htmlData += "<li class='priceHighCol'>High</li>";
  28.             htmlData += "<li class='priceVolumeCol'>Volume</li></ul>";
  29.             for (var i = 0; i < hs.length; i++) {
  30.                 if (i % 2 == 0) {
  31.                     classUL = "priceResultList";
  32.                 }
  33.                 else {
  34.                     classUL = "priceResultList alt";
  35.                 }
  36.                 htmlData += "<ul class='" + classUL + "'>";
  37.                 htmlData += "<li class='priceDateCol'>" + hs[i]._date + "</li>";
  38.                 htmlData += "<li class='pricePriceCol'>" + hs[i]._price + "</li>";
  39.                 htmlData += "<li class='priceHighCol'>" + hs[i]._high + "</li>";
  40.                 htmlData += "<li class='priceVolumeCol'>" + (hs[i]._volume).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + "</li></ul>";
  41.                 pageCount = hs[i]._noOfPages;
  42.             }
  43.             $(".priceResultHolder").html(htmlData);
  44.             if ($(obj).hasClass('next')) {
  45.                 var prevPage = pageNo - 1;
  46.                 var nextPage = pageNo + 10;
  47.                 var lastPage = pageNo + 9;
  48.                 var last = false;
  49.                 if (lastPage > pageCount) {
  50.                     lastPage = pageCount;
  51.                     last = true;
  52.                 }
  53.                 htmlPagination += "<li><a pageno='" + prevPage + "' class='prev' href='javascript:void(0);'><img src='/images/pagination_arrow_prev.png' alt='<' /></a></li>";
  54.                 for (var i = pageNo; i <= lastPage; i++) {
  55.                     if (i == pageNo) {
  56.                         htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  57.                     }
  58.                     else {
  59.                         htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  60.                     }
  61.                 }
  62.                 if (!last) {
  63.                     htmlPagination += "<li><a pageno='" + nextPage + "' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
  64.                 }
  65.                 $(".hsPagination").html(htmlPagination);
  66.                 htmlPagination = "";
  67.             }
  68.             else if ($(obj).hasClass('prev')) {
  69.                 var prevPage = pageNo - 10;
  70.                 var nextPage = pageNo + 1;
  71.                 var firstPage = pageNo - 9;
  72.                 if (pageCount > 10) {
  73.                     if (prevPage != 0) {
  74.                         htmlPagination += "<li><a pageno='" + prevPage + "' class='prev' href='javascript:void(0);'><img src='/images/pagination_arrow_prev.png' alt='<' /></a></li>";
  75.                     }
  76.                     for (var i = firstPage; i < nextPage; i++) {
  77.                         if (i == nextPage - 1) {
  78.                             htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  79.                         }
  80.                         else {
  81.                             htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  82.                         }
  83.                     }
  84.                     htmlPagination += "<li><a pageno='" + nextPage + "' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
  85.                 }
  86.                 $(".hsPagination").html(htmlPagination);
  87.                 htmlPagination = "";
  88.             }
  89.             else if ($(obj).hasClass('priceFilterBtn')) {
  90.                 if (pageCount > 1) {
  91.                     for (var i = 1; i <= pageCount; i++) {
  92.                         if (i == 1) {
  93.                             htmlPagination += "<li><a class='currentSearchPage' pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  94.                         }
  95.                         else {
  96.                             htmlPagination += "<li><a pageno='" + i + "' href='javascript:void(0);'>" + i + "</a></li>";
  97.                         }
  98.                         if (i == 10 && pageCount > 10) {
  99.                             htmlPagination += "<li><a pageno='11' class='next' href='javascript:void(0);'><img src='/images/pagination_arrow_next.png' alt='>' /></a></li>";
  100.                             break;
  101.                         }
  102.                     }
  103.                 }
  104.                 $(".hsPagination").html(htmlPagination);
  105.                 htmlPagination = "";
  106.             }
  107.             else {
  108.                 $('.hsPagination li a').each(function () {
  109.                     $(this).removeClass('currentSearchPage');
  110.                 });
  111.                 $(obj).addClass('currentSearchPage');
  112.             }
  113.             htmlData = "";
  114.         }
  115.     });
  116. }
  117. </script>

Web Service:

  1. [WebMethod(EnableSession = true)]
  2. public List<HistoricalProperty> GetHistoricalPrices(int pageNo, int pageSize, string StDate, string EndDate)
  3. {
  4.     List<HistoricalProperty> historyPricesList = new List<HistoricalProperty>();
  5.     try
  6.     {
  7.         var skipPrices = (pageNo - 1) * pageSize;
  8.         if (Context.Session["historicalPrice"] != null)
  9.         {
  10.             historyPricesList = (List<HistoricalProperty>)Context.Session["historicalPrice"];
  11.             if (StDate.Trim() != "" || EndDate.Trim() != "")
  12.             {
  13.                 historyPricesList = historyPricesList.Where(x => Convert.ToDateTime(x._date) >= Convert.ToDateTime(StDate) && Convert.ToDateTime(x._date) <= Convert.ToDateTime(EndDate)).ToList();
  14.             }
  15.             var totalCount = historyPricesList.Count();
  16.             historyPricesList = historyPricesList.Skip(skipPrices).Take(pageSize).ToList();
  17.             var totalPageCount = 0;
  18.             if (totalCount % pageSize == 0)
  19.             {
  20.                 totalPageCount = totalCount / pageSize;
  21.             }
  22.             else
  23.             {
  24.                 totalPageCount = totalCount / pageSize + 1;
  25.             }
  26.             foreach (var item in historyPricesList)
  27.             {
  28.                 item._totalCount = totalCount;
  29.                 item._noOfPages = totalPageCount;
  30.             }
  31.         }
  32.         else
  33.         {
  34.             SMPHistoricalService.Header HisHeader = new SMPHistoricalService.Header();
  35.             HisHeader.Username = ApplicationConstants._HistoricalHeaderUsername;
  36.             SMPHistoricalService.SMPHIstoricalSplice HisSplice = new SMPHistoricalService.SMPHIstoricalSplice();
  37.             HisSplice.HeaderValue = HisHeader;
  38.             SMPHistoricalService.Untitled HisOutputData = HisSplice.SMPXignite_SMPHIstorical(SMPHistoricalService.IdentifierTypes.Symbol, "", "");
  39.             SMPHistoricalService.Quotes[] Quotes = HisOutputData.GetHistoricalQuotesRangeReturnObject.Quotes;
  40.             //This Splice takes the inputs Identifier, IdentifierType, StartDate, EndDate
  41.             //and calls GetHistoricalQuotesRange to generate Untitled.  
  42.             var totalCount = Quotes.Count();
  43.             var totalPageCount = 0;
  44.             if (totalCount % pageSize == 0)
  45.             {
  46.                 totalPageCount = totalCount / pageSize;
  47.             }
  48.             else
  49.             {
  50.                 totalPageCount = totalCount / pageSize + 1;
  51.             }
  52.             foreach (var quote in Quotes)
  53.             {
  54.                 historyPricesList.Add(new HistoricalProperty
  55.                 {
  56.                     _date = quote.Date,
  57.                     _price = quote.Price.ToString(),
  58.                     _high = quote.High.ToString(),
  59.                     _volume = quote.Volume.ToString(),
  60.                     _totalCount = totalCount,
  61.                     _noOfPages = totalPageCount
  62.                 });
  63.             }
  64.             Context.Session["historicalPrice"] = historyPricesList;
  65.             historyPricesList = historyPricesList.Skip(skipPrices).Take(pageSize).ToList();
  66.         }
  67.     }
  68.     catch
  69.     {
  70.         historyPricesList.Add(new HistoricalProperty { _errorMessage = ApplicationConstants._ServiceErrorMessage });
  71.     }
  72.     return historyPricesList;
  73. }
Wednesday 29 January 2014
Posted by Jebastin

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:

  1. $(function() {
  2. $.cookie("myVar", "Hello World!");
  3. $.cookie("myVar", { path: '/' });   // Sets the cookie at the root level
  4. });

TO READ:

  1. $(function() {
  2.  alert($.cookie("myVar"));
  3. });

TO DELETE:

  1. $(function() {
  2.  $.removeCookie("myVar");
  3. $.removeCookie('myVar', { path: '/' });    // Removes the cookie from the root level
  4. });

CODE VIEW:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>jQuery Session</title>
  5. <script type='text/javascript' src='jquery-1.9.1.js'></script>
  6. <script type="text/javascript" src="jquery.cookie.js"></script>
  7. </head>
  8. <body>
  9. <script type='text/javascript'>
  10. $(window).load(function() {
  11.  // To Store
  12. $(function() {
  13. $.cookie("myVar", "Hello World!");
  14. });
  15. // To Read
  16. $(function() {
  17.  alert($.cookie("myVar"));
  18. });
  19. });
  20. </script>
  21. </body>
  22. </html>
Posted by Jebastin

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:

  1. [WebMethod(EnableSession = true)]
  2. public List<HistoricalProperty> FetchHistoricalData()
  3. {
  4.     List<HistoricalProperty> historyList = new List<HistoricalProperty>();
  5.     if (Context.Session["historicalData"] != null)
  6.     {
  7.         historyList = (List<HistoricalProperty>)Context.Session["historicalPrice"];
  8.         ...
  9.         ...
  10.         ...
  11.     }
  12.     else
  13.     {
  14.         ...
  15.         ...
  16.         ...
  17.         Context.Session["historicalData"] = historyList;
  18.     }
  19.     return historyList;
  20. }

jQuery:

 TO STORE:

  1. $(function() {
  2.  $.session.set("myVar", "Hello World!");
  3. });

TO READ:

  1. $(function() {
  2.  alert($.session.get("myVar"));
  3. });

CODE VIEW:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>jQuery Session</title>
  5. <script type='text/javascript' src='jquery-1.9.1.js'></script>
  6. <script type="text/javascript" src="jquery.session.js"></script>
  7. </head>
  8. <body>
  9. <script type='text/javascript'>
  10. $(window).load(function() {
  11.  // To Store
  12.  $(function() {
  13.  $.session.set("myVar", "Hello World!");
  14.  });
  15. // To Read
  16.  $(function() {
  17.  alert($.session.get("myVar"));
  18.  });
  19.  
  20. });
  21. </script>
  22. </body>
  23. </html>
Posted by Jebastin

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

  1. public class AjaxFileUploader : IHttpHandler
  2. {
  3. public void ProcessRequest(HttpContext context)
  4. {
  5.     if (context.Request.Files.Count > 0)
  6.     {
  7.         string path = context.Server.MapPath("~/Files");
  8.         if (!Directory.Exists(path))
  9.             Directory.CreateDirectory(path);
  10.         var file = context.Request.Files[0];
  11.         string fileName;
  12.         if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
  13.         {
  14.             string[] files = file.FileName.Split(new char[] { '\\' });
  15.             fileName = files[files.Length - 1];
  16.         }
  17.         else
  18.         {
  19.             fileName = file.FileName;
  20.         }
  21.         string strFileName = fileName;
  22.         fileName = Path.Combine(path, fileName);
  23.         file.SaveAs(fileName);
  24.         string msg = "{";
  25.         msg += string.Format("error:'{0}',\n", string.Empty);
  26.         msg += string.Format("msg:'{0}',\n", strFileName);
  27.         msg += string.Format("path:'{0}'", path.Replace("\\", "?"));
  28.         msg += "}";
  29.         context.Response.Write(msg);
  30.     }
  31. }
  32. public bool IsReusable
  33. {
  34.     get
  35.     {
  36.         return true;
  37.     }
  38. }
  39. }

HTML:

  1. <div class="resumeUpload">
  2.     <input type="file" id="fileToUpload" name="fileToUpload" onchange="ajaxFileUpload();" />
  3.     <div class="fileBtn">
  4.         <span>File</span>
  5.         <input id="fileUploadBox" disabled="disabled" value="@GetDictionary("No files selected")" />
  6.     </div>
  7. </div>

jQuery:

  1. <script type="text/javascript">
  2. function ajaxFileUpload() {
  3.     $("#fileToUpload").ajaxStart(function () {
  4.         $('#fileUploadBox').val('Uploading...');
  5.         $('#fileUploadBox').addClass('loadinggif');
  6.     }).ajaxComplete(function () {
  7.         $('#fileUploadBox').removeClass('loadinggif');
  8.     });
  9.     $.ajaxFileUpload({
  10.         url: '/GenericHandlers/AjaxFileUploader.ashx',
  11.         secureuri: false,
  12.         fileElementId: 'fileToUpload',
  13.         dataType: 'json',
  14.         data: { name: 'logan', id: 'id' },
  15.         success: function (data, status) {
  16.             if (typeof (data.error) != 'undefined') {
  17.                 if (data.error != '') {
  18.                     //alert(data.error);
  19.                 } else {
  20.                     $('#fileUploadBox').val(data.msg);
  21.                     $("#hdnFilePath").val(data.path + "?" + data.msg);
  22.                 }
  23.             }
  24.         },
  25.         error: function (data, status, e) {
  26.             //alert(e);
  27.             $('#fileUploadBox').val('File size is too large.');
  28.         }
  29.     });
  30.     $.extend({
  31.         handleError: function (s, xhr, status, e) {
  32.             if (s.error)
  33.                 s.error(xhr, status, e);
  34.             else if (xhr.responseText)
  35.                 console.log(xhr.responseText);
  36.         }
  37.     });
  38.     return false;
  39. }
  40. </script>
Source: Hayageek
Tuesday 21 January 2014
Posted by Jebastin

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.
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>jQuery.trim demo</title>
  6. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  7. </head>
  8. <body>
  9. <pre id="original"></pre>
  10. <pre id="trimmed"></pre>
  11. <script>
  12. var str = "     lots of spaces before and after     ";
  13. $( "#original" ).html( "Original String: '" + str +"'");
  14. $( "#trimmed" ).html( "Trimmed String: '" + $.trim(str) +"'");
  15. </script>
  16. </body>
  17. </html>
Posted by Jebastin
Tag : ,

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" />
Posted by Jebastin
Tag :

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:
  1. @Model.CreateDate
To get the Last Published Date of an Umbraco Node:
  1.  @Model.UpdateDate
Posted by Jebastin

How to get the value of a CSS property using jQuery?

Consider the following HTML:
  1. <div id="jjTechSol" style="height: 50px;width: 50px;">
  2.  <p>Content</p>
  3.  </div>
The following jQuery is used to get the value of a CSS property.
  1. <script type="text/javascript">
  2. $(document).ready(function () {
           alert('Height:'+$("#jjTechSol").css('height'));
  3.        alert('Width:'+$("#jjTechSol").css('width'));
    });
  4. </script> 
.css( propertyName ) gets the value of style properties for the first element in the set of matched elements.
     propertyName
     Type: String    
     A CSS property.
Wednesday 15 January 2014
Posted by Jebastin
Tag : ,

How to Compare two fields with jQuery validate plugin?


Consider the following HTML.
  1. <input type="text" id="txtEmail" name="Email"  />
  2. <input type="text" id="txtConfirmEmail" name="ConfirmEmail" /> 
The following script is used to Compare two fields with jQuery validate plugin.
  1. $('#myform').validate({
  2.     rules: {
  3.         Email: { required: true },
  4.         ConfirmEmail: { equalTo: '#txtEmail' }
  5.     }
  6. });
Wednesday 8 January 2014
Posted by Jebastin

How to convert the first character of a string into upper case?

The following C# code is used to convert the first character of a string into upper case.
  1. static string UppercaseFirst(string s)
  2. {
  3. // Check for empty string.
  4. if (string.IsNullOrEmpty(s))
  5. {
  6.     return string.Empty;
  7. }
  8. // Return char and concat substring.
  9. return char.ToUpper(s[0]) + s.Substring(1);
  10. }
Tuesday 7 January 2014
Posted by Jebastin
Tag :

How to convert all first letters of a sentence into upper case and rest of the letters into lower case?

The following C# code is used to convert all first letters of a sentence into upper case and rest of the letters into lower case.
  1. string s = "THIS IS MY TEXT RIGHT NOW";
  2. s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
  3. // (or)
  4. s = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
Posted by Jebastin
Tag :

How to check whether an Umbraco Node has children or not?

The following Razor code is used to check whether an Umbraco Node has children or not.
  1. bool hasChildren = (Model.ChildrenAsList.Count() > 0);
  2. if(hasChildren)
  3. {
  4.     //code
  5. }
  6. else
  7. {
  8.     //code  
  9. }
Posted by Jebastin

Razor function to fetch the Data Type Items in Umbraco

The following Razor function is used to fetch the Data Type Items in Umbraco.

Namespaces Required:
using System.Xml.XPath;
using umbraco.MacroEngines;
  1. @functions{
  2.     public List<string> FetchDataTypeItems(int DataTypeNodeID)
  3.     {
  4.         XPathNodeIterator preValueRootElementIterator = umbraco.library.GetPreValues(DataTypeNodeID);
  5.         preValueRootElementIterator.MoveNext();
  6.         XPathNodeIterator preValueIterator = preValueRootElementIterator.Current.SelectChildren("preValue", "");
  7.         List<string> DataTypeListItems = new List<string>();
  8.         while (preValueIterator.MoveNext())
  9.         {
  10.             DataTypeListItems.Add(preValueIterator.Current.Value);
  11.         }
  12.         string[] CommonTerms = DataTypeListItems.ToArray();
  13.         return DataTypeListItems;
  14.     }
  15. }
Monday 6 January 2014
Posted by Jebastin

How to get the URL of the current page

The following code is used to get the URL of the current page.

  1. string url = HttpContext.Current.Request.Url.AbsoluteUri;
  2. // http://localhost:1302/TESTERS/Default6.aspx

  1. string path = HttpContext.Current.Request.Url.AbsolutePath;
  2. // /TESTERS/Default6.aspx

  1. string host = HttpContext.Current.Request.Url.Host;
  2. // localhost

You may need to get different values from URL.

Below example shows different ways of extracting different parts of URL

EXAMPLE (Sample URL)

http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2

  1. Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
  2. Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
  3. Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
  4. Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
  5. Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
  6. Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);

OUTPUT
  1. localhost
  2. localhost:60527
  3. /WebSite1test/Default2.aspx
  4. /WebSite1test
  5. http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
  6. /WebSite1test/Default2.aspx?QueryString1=1&QuerrString2=2
Saturday 4 January 2014
Posted by Jebastin
Tag :

Link To This Post/Page

Spread The Word

Add this button to your blog:
JJ Technology Solutions

Blog Archive

Trackers

eXTReMe Tracker
facebook

- Copyright © JJ Technology Solutions - Powered by Source Code Solutions -