Search This Blog

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, February 8, 2011

FileUpload Control Validation

With FileUpload control you can receive files from your web application users. Often, you don't want to receive all file types, but only specific extensions (e.g. images only) depending of your application requirements. Unfortunately, FileUpload control still have not some Filter property like Open and Save File dialogs in .NET Windows Forms to limit file types. Because of that, you need to write some additional code to be sure that user will upload regular file type.

Let say you have two web controls on web form, on FileUpload Control to select a file and one button control

Because in ASP.NET we have client and server side, validation could be done on client and on server. You need to have server side validation because of security reasons, but you also need client side validation because it is faster and more user friendly. Let see how to implement both types, for example our web application will allow only upload of .xls or .xml files.

FileUpload Control client side validation


You can use CustomValidator to implement FileUpload validation on client side. Possible implementation could be with code like this:


<asp:FileUpload ID="fuData" runat="server" />
&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload" />
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server"
 ClientValidationFunction="ValidateFileUpload" ErrorMessage="Please select valid .xls or .xml file"></asp:CustomValidator>
<script language="javascript" type="text/javascript">
    function ValidateFileUpload(Source, args) {
        var fuData = document.getElementById('<%= fuData.ClientID %>');
        var FileUploadPath = fuData.value;

        if (FileUploadPath == '') {
            // There is no file selected
            args.IsValid = false;
        }
        else {
            var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

            if (Extension == "xls" || Extension == "xml") {
                args.IsValid = true; // Valid file type
            }
            else {
                args.IsValid = false; // Not valid file type
            }
        }
    }
</script> 

If visitor tries to upload wrong file type or FileUpload have empty value, CustomValidator will return an error message.

FileUpload Control server side validation


Because of security reasons, you need to validate FileUpload control on server side too. You can use the same idea like for client side validation. In this case, just use OnServerValidate event, like in code bellow:


 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    // Get file name
    string UploadFileName = fuData.PostedFile.FileName;

    if(UploadFileName == "")
    {
      // There is no file selected
      args.IsValid = false;
    }
    else
    {
        string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).toLower();

        if (Extension == "xls" || Extension == "xml")
        {
          args.IsValid = true; // Valid file type
        }
        else
        {
          args.IsValid = false; // Not valid file type
        }
    }
}




Now is your FileUpload Control protected on client and server side. I hope you found this tutorial helpful

Thursday, February 3, 2011

Refresh an Update Panel using JavaScript


I have noticed a lot of discussion regarding methods to refresh an UpdatePanel via client script. This is very easy on the server side, of course. You can just call UpdatePanel.Update(). However, on the client side, the most common solutions I have been seeing just don’t feel right.

Many will advise you to use a hidden button control inside the UpdatePanel, manipulated via button.click(), to trigger a partial postback of the UpdatePanel. While it does work, I never have been able to get past the inelegant solution for this problem.


To find a better solution, we’ll need a demonstration UpdatePanel to experiment with:



<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="Container">
<asp:UpdatePanel runat="server" ID="UpdatePanel1" 
    OnLoad="UpdatePanel1_Load">
  <ContentTemplate>
    <asp:Label runat="server" ID="Label1" />
  </ContentTemplate>
</asp:UpdatePanel>

protected void UpdatePanel1_Load(object sender, EventArgs e)
{
  Label1.Text = DateTime.Now.ToString();
}

That’s a slightly modified version of the standard UpdatePanel DateTime 

hat the UpdatePanel’s OnLoad event is handled in code-behind. Anytime UpdatePanel1 is loaded or reloaded in a postback, Label1 will b
example. Instead of the more commonly used Button_Click trigger, notice te updated to reflect the current date and time. Luckily, there’s an easy method for triggering a postback targeted at the UpdatePanel: __doPostBack(). As long as the event target of a __doPostBack() call is an async trigger of an UpdatePanel, the ASP.NET AJAX framework will intercept the postback and 
fire a partial postback instead. For purposes of demonstration, I’m going to 
add that to the OnClick event of the container div:

<div id="Container" onclick="__doPostBack('UpdatePanel1', '');">

Now, clicking anywhere in the UpdatePanel will trigger a partial postback, 
targeting the UpdatePanel. Since partial postbacks follow the full page lifecycle
this will fire UpdatePanel1_Load and update the Label’s text.

A word on _doPostBack
You may have noticed that there is also an ASP.NET AJAX specific method of 
the PageRequestManager named _doPostBack. While it works much like
__doPostBack, as long as the ASP.NET AJAX client framework is 
present, you should not call it directly. 
The original __doPostBack method performs identically, but is more robust 
since it gracefully degrades to full postbacks when the ASP.NET AJAX framework 
isn’t available. It’s also unlikely that __doPostBack will disappear in future 
versions of ASP.NET, while it’s less assured that the ASP.NET AJAX framework 
will remain unchanged.

Tuesday, September 7, 2010

Java Script GridView ClientSide Validation


I am going to explain the simple GridView Client Side Validation instead of server side validation controls.

Performing the Client side validation on GridView Itemtemplate controls is quite tedious and finding the controls it seems to difficult.This snippet below validates all controls using JS.The article explains the GridView Client Side Validation instead of server side validation controls.

JavaScript 

<script language="javascript" type="text/javascript">
  function check()
   {
    var grid = document.getElementById('<%= GridView1.ClientID %>');
     if(grid!=null)
      {
       var Inputs = grid.getElementsByTagName("input");
        for(i = 0; i < Inputs.length; i++)
         {
          if(Inputs[i].type == 'text' )
           {
            if(Inputs[i].id == 'GridView1_ctl02_txtName')
             {
              if(Inputs[i].value=="")
               {
                alert("Enter Name ");
                return;
               }
             }
         if(Inputs[i].id == 'GridView1_ctl02_txtEmail')
             {
                if(Inputs[i].value=="")
               {
                alert("Enter Email");
                  return;
               }
               var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
               var emailid =Inputs[i].value;
               var matchArray = emailid.match(emailPat);
               if (matchArray == null)
                 {
                   alert("Your email address is not valid.");
                   return; 
                 }
              }
            }        }
    }
}
</script>


1. First of all I am finding the Giridview using the ClientID , then the type of controls Input and the ID of the Controls.
2.The GridElementsByTagName returns the unique Id of the controls (For Ex:'GridView_ctlo2_txtName')
3.Using this Id we have to check the null valus and other validations.

GridView Code

<form runat="server">
 <asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="NEW" />
    <asp:Button ID="Button1" runat="server" OnClick="btnCancel_Click" Text="CANCEL" style="position: relative" />
        <asp:GridView ID="GridView1" runat="server"
          AutoGenerateColumns="false"
           OnRowEditing="GridView1_RowEditing" 
           OnRowCommand="GridView1_RowCommand" 
        Style="left: 324px; position: relative;         
            top: 86px" Width="308px">
            <Columns>
            <asp:TemplateField HeaderText="Name"> 
            <ItemTemplate>
            <table>
            <tr>
            <td>
             <asp:TextBox ID="txtName"  Visible="false"  runat="server"></asp:TextBox>
            </td>
            </tr>
            <tr>
            <td>
             <asp:Label ID="lblname" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"name")%>'></asp:Label>
            </td>
            </tr>
            </table>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Email"> 
             <ItemTemplate>
             <table>
            <tr>
            <td>
            <asp:TextBox ID="txtEmail" Visible="false" runat="server"></asp:TextBox> 
           </td>
            </tr>
            <tr>
            <td>
           <asp:Label ID="lblemail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"eml")%>'></asp:Label>
            </td>
            </tr>
            </table>
            </ItemTemplate>
            </asp:TemplateField>
           </Columns>           
        </asp:GridView>   
    </div>
    </form>

4.On the Page_load event add the Button.Attributes.Add onclick event client function.
Code Behind
 protected void Page_Load(object sender, EventArgs e)
    {
        btnEdit.Attributes.Add("onclick", "return check()");   
    }