Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Saturday, July 23, 2011

Validate different controls on different buttons in a same page

 

Normally developers have a requirement to validate different controls on different buttons in this situation developers face problem when user click on any button all validation will be fire which are not belongs to that button functionality.

ASP.NET V2 introduces a new “ValidationGroup” property on validation and input controls that now makes this possible. This allows page developers to group different controls together for more granular validation behavior.

For example two groups – a “Group1” and a “Group2” of validators. There are then two buttons on the page – when button1 is clicked, the first group of validators will fire. When button2 is clicked, the second group of validators will fire. Postback will be blocked client-side by default if the validation fails:

 

Client Side Validation

<html>
<body>
     <form runat=“server”>
          <asp:textbox id=“TextBox1” runat=“server”/>
          <asp:requiredfieldvalidator ValidationGroup=“Group1” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox1” runat=“server”/>
            <asp:textbox id=“TextBox2” runat=“server”/>
            <asp:requiredfieldvalidator ValidationGroup=“Group2” ErrorText=“Need to Fill in Value!” ControlToValidate=“TextBox2” runat=“server”/>
            <asp:button text=“Group1” ValidationGroup=“Group1” runat=“server”/>
            <asp:button text=“Group2” ValidationGroup=“Group2” runat=“server”/>
     </form>
</body>
 
</html>
 

The code given above has two validation groups. The first validation groups is identified as “First” and the second validation group is identified as “Second”. Each validation group has two textboxes, a RequiredField validator and a button. If you look at the code you might see that each control has a property called “ValidationGroup” and its value is set to the name of the validation group to which that control belongs.


Clicking the “Submit1” button initiates the validation of the first group and throws an error message if the TextBox1 is left blank. Since this button belongs to the ‘First’ validation group, it initiates the validaton controls that belongs to that group. Similarly clicking the ‘Submit2’ button throws an error message if the TextBox3 is left blank. Thus the validation groups help in grouping the controls in a single web page allowing you to have separate validations for different controls while allowing you to submit values in a particular group.


 


Server Side Validation


If you want to validate on server side just call page.Validate(“Group Name”) on button click event it will automatically call respective group.You don’t have need to define specific group on html code.



<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Runat="server" ValidationGroup="First"></asp:TextBox>
<asp:TextBox ID="TextBox2" Runat="server" ValidationGroup="First"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" ValidationGroup="First"ErrorMessage="TextBox1 should not be blank" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>
<asp:Button ID="Submit1" Runat="server"  Text="Submit 1" />
 <br /><br /> 
<asp:TextBox ID="TextBox3" Runat="server" ValidationGroup="Second"></asp:TextBox> 
<asp:TextBox ID="TextBox4" Runat="server" ValidationGroup="Second"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server" ErrorMessage=" TextBox3 should not be blank"ControlToValidate="TextBox3" ValidationGroup="Second"></asp:RequiredFieldValidator>
 <asp:Button ID="Submit2" Runat="server"  Text="Submit 2" />
 </div>
</form>
</body> 

 



protected void Submit1_Click(object sender, EventArgs e)
{
 
Page.Validate("First");
 
if(Page.IsValid)
    {
        // Continue
    }
}
 
protected void Submit2_Click(object sender, EventArgs e)
{
 
Page.Validate("Second");
 
if(Page.IsValid)
    {
        // Continue
    }
}
  




      

Monday, May 23, 2011

Define Access Key In asp.net button control

Flickr Tags: ,

If you want to underline and define the access key in asp.net just like you define in windows application , use the html button element. To produce the same behavior as an asp.net Button control. I set the runat attribute to "server" and use the onclick event to call javascript and onServerClick event to call a server side method.


Here is the code for the page,

<form id="form1" runat="server">



<button id="hbutton1" runat="server" type="submit" accesskey="A" onserverclick="hbutton1_Click" onclick="alert('test');"><u>A</u>dd</button>



</form>




Code-behind, 
 





protected void hbutton1_Click(object sender, EventArgs e)



       {



           Response.Write("hbutton clicked");



       }




When, the page is run, a button is generated with text "Add". When clicked, at first an alert message is shown and then the page postbacks.

Sunday, May 22, 2011

Register Custom User Control in Web.Config File

 

Normally we register any user control or assemblies in page directive of aspx html source if we want to used in any aspx page like.

 


<%@ Register TagPrefix="MyControl" TagName="HeaderControl" Src="Header.ascx" %>
<%@ Register TagPrefix="MyControl" TagName="footerControl" Src="Footer.ascx" %>
<%@ Register TagPrefix="MyAssembly" Assembly="Myassembly" %>
 
 
IF you have header and footer user control and you want to adding on every page or more than one pages then you don’t need to register on every page just register only one time in web.config file and used it multiple time like this way.


<?xml version="1.0"?>
<configuration>
<system.web>
 
        <pages>
        <controls>
        <add tagPrefix="MyControl" src="~/Header.ascx"
        tagName="HeaderControl"/>
        <add tagPrefix="MyControl" src="~/Footer.ascx"
        tagName="footerControl"/>
        <add tagPrefix="MyAssembly" assembly="MyAssembly"/>
        </controls>
        </pages>
        
</system.web>
</configuration>



Wednesday, April 13, 2011

Block or Disable Cut, Copy and Paste operation in ASP.Net

 
Block or Disable Cut, Copy and Paste operation in ASP.Net TextBox Using jQuery

It is required to block the cut, copy and paste operations on some of the textbox in an ASP.Net. For example, it will be better if we do not allow users to copy paste the data entered in Email and Confirm Email field in order to make the user to type themselves.

The below jQuery code will help us to do the same using preventDefault() method.

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
    <script type="text/javascript">
        $(function() {
        $("#<% =txtEmail.ClientID %>,#<% =txtConfirmEmail.ClientID%>").bind("cut copy paste", function(event) {
                event.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <b>Email </b><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
        <b>Confirm Email </b><asp:TextBox ID="txtConfirmEmail" runat="server"></asp:TextBox>

 

Block Right Click in asp.net  

If you want to block right click copy code in master page.

<SCRIPT language=JavaScript>
<!--  -->
    var message = "function disabled";
    function rtclickcheck(keyp){ if (navigator.appName == "Netscape" && keyp.which == 3){     alert(message); return false; }
    if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) {     alert(message);     return false; } }
    document.onmousedown = rtclickcheck;
</SCRIPT>

Friday, February 4, 2011

Avoid Multiple Form Submits

 
Multiple form submits is a serious issue in web applications because it’ll result in unexpected behavior like multiple entries in database .I have spent some time for the same in Google and I got some solutions for that.
If you are submitting the page only once then you can use,
<form onsubmit="return Submit();">
And the method is like,
 

<script type="text/javascript">
var flag = false;
function Submit() {
if (flag) {
return false;
}
else {
flag = true;
return true;
}
}
</script>
 



For a single button you can use,

 
btnSubmit.Attributes["onclick"] = "this.disabled=true;" + GetPostBackEventReference(btnSubmit);




 


For pages with update panels multiple submit is a serious issue as page is posting asynchronously or partially.In that scenario you can use Sys.WebForms.PageRequestManager for fixing the issue,

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
function BeginRequest(sender, e) {
e.get_postBackElement().disabled = true;
}
</script>

Tuesday, February 1, 2011

Auto-Refreshing ASP.NET Web Pages

 

Today I am writing about how you can auto-refresh the page without user click .If you want to refresh the page at specific time of interval like after each 10 seconds you can used any of the following methods.

HTML header refresh tag

 

    The most common and best known way to tag of the following format is placed in the HTML section of the page:

    <meta http-equiv="refresh" content=" 5; url=http://dotnetfarrukhabbas.blogspot.com/">

    • where '5' refers to the number of seconds that will elapse before the page is refreshed;

    • 'url' is the new url redirect to. It can be excluded which means the current page will be reloaded.

      This construct is useful if you have one or two pages which have to auto-refresh, and works for any HTML content type forms.

      You can used this meta tag in master page as well as any specific page.

       

      Using JavaScript

      You can also used the JavaScript for auto refreshing the page instead of meta tag.

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

      setTimeout("StratRefresh()", 30000);
      function StratRefresh() {
      window.location.reload();
      }
      </script>



       


      Refresh Page from Server Side


      ASP.NET provides the AppendHeader method to the Response object. Typically the page refresh can be set as follows in an ASP.NET webform (in C#):

      protected void Page_Load(object sender, EventArgs e)
      {
      if (!Page.IsPostBack)
      {
      //page will be refereshed at a interval of 10 sec
      Response.AddHeader("Refresh", "10");
      }
      }



      This construct is useful as it can be placed in a base webform OnLoad() or Page_Load() response method. All derived webforms will then have the same page refresh setting when they are loaded.


      Note 


      when the page gets refresh then it will not persist the view-state of the page.

      Tuesday, December 28, 2010

      Request.Url parameters & details (Asp.net)

       

      Here I will explain you Request.Url Parameters and its details.

      Full URL : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue

      Request.ApplicationPath : /virtual_dir
      Request.CurrentExecutionFilePath : /virtual_dir/myrep/page.aspx
      Request.FilePath : /virtual_dir/myrep/page.aspx
      Request.Path : /virtual_dir/myrep/page.aspx
      Request.PhysicalApplicationPath : d:\Inetpub\wwwroot\Websitename\virtual_dir\
      Request.QueryString : /virtual_dir/myrep/page.aspx?q=qvalue
      Request.Url.AbsolutePath : /virtual_dir/myrep/page.aspx
      Request.Url.AbsoluteUri : http://localhost:2000/virtual_dir/myrep/page.aspx?q=qvalue
      Request.Url.Host : localhost
      Request.Url.Authority : localhost:2000
      Request.Url.LocalPath : /virtual_dir/myrep/page.aspx
      Request.Url.PathAndQuery : /virtual_dir/myrep/page.aspx?q=qvalue
      Request.Url.Port : 2000
      Request.Url.Query : ?q=qvalue
      Request.Url.Scheme : http
      Request.Url.Segments : /
      virtual_dir/
      myrep/
      page.aspx

      Sunday, December 26, 2010

      C# String Tips

      Technorati Tags:

      The .NET string class is quite comprehensive, yet some common string functions are missing or not entirely obvious. This article provides quick tips on using .NET strings.

      Fill a String with Repeating Characters

      To fill a string with repeating characters, use the string class constructor. For example, to fill a string with twenty asterisks:

      string s = new string( '*', 20 );


      Check for Blank String



      A blank string can be represented by a null reference or empty string (String.Empty or ""). If you attempt to call a method on a null string, an exception will occur. Hence, to check for a blank string, you should use the new .NET v2.0 static function String.IsNullOrEmpty:

      String.IsNullOrEmpty( s )


      String.Empty vs. ""? It Doesn't Matter



      There has been endless debate on the Web whether it's better to represent an empty string with String.Empty or blank quotes "". However, tests show there is minimal performance difference between String.Empty and "" even when creating a billion empty strings.

      Reverse a String



      There has been extensive analysis on algorithms to reverse a string. The following is a good balance between speed and clarity and works well with Unicode and alternate character sets:

      static public string Reverse( string s )
      {
      char[] charArray = s.ToCharArray();
      Array.Reverse( charArray );
      return new string( charArray );
      }


       

      Compare Strings



      Because a string reference can be null, you should avoid using the equality symbol == or the Compare member function when comparing strings. Instead, use the static String.Compare method. This method has the advantage that it can handle null string references, compare strings ignoring case, and compare strings using a specific culture:

      if (String.Compare( s1, s2, true ) == 0)


       

      Convert String to Numeric Value



      Each numeric data type such as int, Int32, double, etc. has a static TryParse method that converts a string to that data type without throwing an exception. The method returns a bool whether the string contained a value with the specified data type. For example:

      string s = "42";
      int i;
      int.TryParse( s, out i );


       

      Use Literal Strings for File Paths



      A literal string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters. This makes literal strings ideal for file paths that naturally contain many backslashes. To create a literal string, add the at-sign @ before the string's opening quote. For example:

      string path = @"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe";


       

      String Right



      Noticeably absent from the string class is the Right method. But you can replicate it easily using the Substring method. Here is a simple method that wraps this up nicely:

      static string Right( string s, int count )
      {
      string newString = String.Empty;
      if (s != null && count > 0)
      {
      int startIndex = s.Length - count;
      if (startIndex > 0)
      newString = s.Substring( startIndex, count );
      else
      newString = s;
      }
      return newString;
      }



       

      IndexOf Ignoring Case



      The string's IndexOf methods are all case-sensitive. Fortunately, the Globalization namespace contains the CompareInfo class that includes a case-insensitive IndexOf method. For example:

      using System.Globalization;


      string s1 = "C# is a GREAT programming language.";
      string s2 = "great";

      CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
      int i = Compare.IndexOf( s1, s2,CompareOptions.IgnoreCase);

      PDF Arabic watermark using MVC and iTextSharp

      PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...