Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

July 17, 2014

jQuery Validation and jQuery Unobtrusive Validation are validation frameworks for validating data in web pages. The main difference between the two is that jQuery Validation requires javascript codes to be entered in the page whereas jQuery Unobtrusive Validation requires the validation related data to be available in the data- attributes for the html elements. So, with the first option, the html elements will contain javascripts in it whereas with the later, the code will be lot cleaner.

May 6, 2014

jQuery not working within Update Panel

I wrote this jQuery validation for a site and it all worked in my test page but for some reason it stopped working in the real page. Since the real page is a currently live, I started creating and testing the validation on the dummy page first. After some debugging for finding the issue, I realised that the jQuery is not running within the actual page since the controls and html elements are within the Update Panel.

April 29, 2014

Data attributes are a cool way to store extra data for html elements. Previously, when we needed to store additional data for an html element we would store it hidden elements whereas now with data attributes, we can store it within the html element itself as shown below.

  1. <li data-test="test">data</li>

 

Since data attributes are standard html attributes, we can use it within asp.net as well. Here's an example on how we can load country / capital data within a ListView control, store the capital information as data attribute and then display the capital when the user hovers over the country using jQuery.

April 22, 2014

In this post, I will show how to upload multiple files at once using the File Upload control and jQuery's uploadify plugin. Download the Uploadify plugin if you have not already done so. Copy the uploadify.css, uploadify.min.js and uploadify.swf to your project in appropriate folders. For example, I have copied the javascript file to scripts folder and so on. Using javascript, I will specify the file types that can be uploaded using the "fileExt" parameter. Also, I have assigned paths to the swf and a handler. The handler is the file that will handle the request unlike the usual way of performing file uploads within the code behind file. Here's the source code for the page.

aspx
  1. <!DOCTYPE html>
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5.     <title></title>
  6.     <script src="scripts/jquery.min.js"></script>
  7.     <script src="scripts/jquery.uploadify.min.js"></script>
  8.     <link href="css/uploadify.css" />
  9.     <script type="text/javascript">
  10.         $(function () {
  11.             $("#<%=FU1.ClientID %>").uploadify({
  12.                 'swf': 'scripts/uploadify.swf',
  13.                 'uploader': '/Handler/FileHandler.ashx',
  14.                 'cancelImg': 'cancel.png',
  15.                 'buttonText': 'Choose Files to Upload',
  16.                 'fileDesc': 'Image Files',
  17.                 'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
  18.                 'multi': true,
  19.                 'auto': true
  20.             });
  21.         })
  22. </script>
  23. </head>
  24. <body>
  25.     <form id="form1" runat="server">
  26.     <div>
  27.     <asp:FileUpload ID="FU1" runat="server" />
  28.     </div>
  29.     </form>
  30. </body>
  31. </html>


The Handler basically gets the files uploaded and the saves it to a specified folder. In this instance, I am saving it to the UserFiles folder within the application. Make sure you have already created the folder with the correct permissions (read / write attributes). Here's the source code for the handler.

File Upload Handler
  1. public class FileHandler : IHttpHandler
  2. {
  3.  
  4.     public void ProcessRequest(HttpContext context)
  5.     {
  6.         context.Response.ContentType = "text/plain";
  7.         HttpPostedFile uploadFiles = context.Request.Files["Filedata"];
  8.         string pathToSave = HttpContext.Current.Server.MapPath("~/UserFiles/") + uploadFiles.FileName;
  9.         uploadFiles.SaveAs(pathToSave);
  10.     }
  11.  
  12.     public bool IsReusable
  13.     {
  14.         get
  15.         {
  16.             return false;
  17.         }
  18.     }
  19. }

January 7, 2014

Consume Web Service using jQuery

jQuery is a javascript library than can be used to call web services among many other functions. In this example, I will create a web service using asmx and use jQuery to pass and retrieve data from the web service using json. This is really useful as this means we can consume the web service from any platform like jsp, php and not only from asp.net. I have used json for transmitting data and it is in a platform independent technology that transmits data in an "attribute : value" format.

For this example, I will start with the web service. It's going to be asmx service that simply adds and subtracts numbers that it retrieves from the front end. Here's the code for the web service.

web service
  1. using System.Web.Services;
  2.  
  3. namespace WebApplication1
  4. {
  5.     [WebService(Namespace = "http://tempuri.org/")]
  6.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  7.     [System.ComponentModel.ToolboxItem(false)]
  8.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
  9.     [System.Web.Script.Services.ScriptService]
  10.     public class WSPrac : System.Web.Services.WebService
  11.     {
  12.         [WebMethod]
  13.         public double Add(double a, double b)
  14.         {
  15.             return a + b;
  16.         }
  17.  
  18.         [WebMethod]
  19.         public double Substract(double a, double b)
  20.         {
  21.             return a - b;
  22.         }
  23.     }
  24. }


The code self explanatory. The important bit to note is that the line "[System.Web.Script.Services.ScriptService]" needs to be uncommented. This will allow the service to be called using javascript.

On the front end, I have couple of text fields, 1 option field to select to add or to subtract, a button that will trigger the script when clicked and a span element that will display the data. Here's the code for the html front end.

html front end
  1. <body>
  2.     <input type="text" id="t1" />
  3.     
  4.     <select id="sel">
  5.         <option value="Substract">Substract</option>
  6.                 <option value="Add">Add</option>
  7.     </select>
  8.     
  9.     <input type="text" id="t2" />
  10.     <input type="button" id="b2" value="Calc" /><br />
  11.     <span id="span1"></span>
  12. </body>


In the last bit is the javascript section. Here's the code for this.

jQuery block
  1. <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  2.        <script type="text/javascript">
  3.  
  4.     $(document).ready(function () {            
  5.         $('#b2').click(function () {
  6.             var url = "WSPrac.asmx/" + $('#sel').val();
  7.             $.ajax({
  8.                 type: "POST",
  9.                 contentType: "application/json; charset=utf-8",
  10.                 url: url,
  11.                 data: "{ a: '" + $('#t1').val() + "',  b: '" + $('#t2').val() + "'}",
  12.                 dataType: "json",
  13.                 success: function (data) {
  14.                     $("#span1").html(data.d);                  
  15.                 },
  16.                 error: function () {
  17.                     $("#span1").html("Error!!!");
  18.                 }                   
  19.         });
  20.     });
  21.     });
  22. </script>


To start with I am calling jquery source file. Next, in the button click handler, I am forming the service url based on the selection. The important bit is this line

  1. data: "{ a: '" + $('#t1').val() + "',  b: '" + $('#t2').val() + "'}"

 

Note that a and b are parameter names in the service and I am sending the value of the text boxes. Finally, on success, I am populating the data in the span element. In case, error occurs, for example, if we type in "abc" in the text box or the web service is down, then the error function is fired and the text "Error!!!" is displayed within the span element.

Another thing to note is that the return value in json has .d at the end. This is within the success function as below.

  1. success: function (data) {
  2.     $("#span1").html(data.d);                  
  3. }


The .d is a wrapper that ensures the payload is a json object.

Reference: Shahed Kazi at AspNetify.com