Skip to main content

Javascript tips for ASP.Net


We can use Javascript whenever we need to do some clientside operations in asp.net. There are so many Javascript operations which we repeatedly use in our applications. This article will list some of the repeated Javascript utilities, which we can use in our asp.net application.
Moving forward this article will discuss about,
Ø       MaxLength in ASP:Textbox Control.
Ø       Passing Date from Calendar Pop-Up to Parent Window.
Ø       Clear File Upload Control.
Ø       Restricting the user copying the Page Text.

 MaxLength in ASP:TextBox Control
To restrict the length of a textbox control we can set the maximum length with a property called MaxLength. But, when we use the ASP.Net TextBox control as a multiline TextBox by setting TextMode property as MultiLine, the MaxLength property will not work. It is because the multiline textbox will be rendered as <TextArea> which does not support maximum length property (MaxLength). 

The below JavaScript function can be used to restrict the user from entering more than restricted length.
function limitCharsLength(Object, MaxLen)
{
if(Object.value.length > (MaxLen-1))
 {
    return false;  
 }
}
<asp:TextBox ID="TextBox2" runat="server" onkeypress="javascript: return limitCharsLengthDefault(this,10);" Rows="10" TextMode="MultiLine"></asp:TextBox>

Drawback of the above method
The above function will restrict the user to type more than 10 characters in the textbox but it does not validate the maximum length when the user copy pastes the content from elsewhere into the text box. So, the above function can be rewritten as,

function limitCharsLength(Object, MaxLen)
{
if(Object.value.length > MaxLen-1)
{
Object.value= Object.value.substring(0,MaxLen);
}
}
<asp:TextBox runat="server" ID="txtComments" onkeypress="javascript: return limitCharsLength(this,300);"  onblur="javascript:return limitCharsLength(this, 300)" onchange="javascript : return limitCharsLength(this, 300)" TextMode="MultiLine" Rows="10"></asp:TextBox>

This function will not allow a user to type or copy paste contents with length greater than the specified length.

Passing Date from Calendar Pop-Up to Parent Window
This section will help us building a simple DatePicker control using Calendar control and Javascript. Create two aspx pages, Default.aspx and Calendar.aspx. Calendar.aspx will contain a Calendar control and it should be opened as a popup window. When the user selects a date in the Calendar popup it will populate the date selected into a textbox in the Default.aspx page.
Default.aspx
1) Drag a TextBox and name it as ‘txtDate’.
2) Drag an Html Button and change the text as ‘Date’.

Write a JavaScript function to open the popup that is containing the Calender Control.

function PopupPicker(ctl)
{
var PopupWindow=null;
PopupWindow=window.open('Calender.aspx?ctl='+ctl,'','width=250,height=250’);
PopupWindow.focus();
}

Pass the textbox control id to the popup windows in a QueryString (ctl), so that the popup window can populate the textbox control with the date selected in the Calendar control.

<input id="Button2" type="button" value="Click" onclick="PopupPicker('txtDate');"/>

Calender.aspx
1) Drag a Calendar Control to the webform.
2) Get the TextBox Control Name which is sent in query string.
3) Create a JavaScript function called “SetDate” which accepts 2 parameters, dateValue and ctl. dateValue is the date selected by the user in the calendar popup and ctl is the parent page control id where we need to populate the date selected.
(The code is self explanatory).
function SetDate(dateValue,ctl)
{
thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue;
self.close();
}

4) In clnDatePicker_DayRender Event, write the following code to call a javascript function ‘SetDate’.

HyperLink hpl = new HyperLink();
hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text;
hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() + "','"+ctrl+"');";
e.Cell.Controls.Clear();
e.Cell.Controls.Add(hpl);

By default, the days in calendar control is rendered as links and generate a postback when it is clicked. Instead of postback, we will call our custom SetDate() JavaScript function by changing the cell of the Calendar control to Hyperlink control and attaching the SetDate() JavaScript function to the hyperlink in clnDatePicker_DayRender event.

Clear File Upload Control
The following javascript function can be used to clear a FileUpload control in ASP.Net 2.0.
  <script language="javascript">
    function ClearFileUpload()
    {
    var fil = document.getElementById("FileUpload1");
   fil.select();
   n=fil.createTextRange();
   n.execCommand('delete');
   fil.focus();     
    }
    </script>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" OnClientClick="ClearFileUpload()" Text="Button" />

Restricting the user copying the Page Text
We can restrict users copying the text in our page by using a simple Jscript code.

<script language="JavaScript">
document.onselectstart=new Function ("return false");
</script>

One another way of restricting the users block copying the text is by disabling the right click on the webpage.
The following script is taken from a Microsoft KB article Q286426 and it only works with IE.

<script language="JavaScript">
var message = "Sorry, that function is disabled.\n\n";
message += "This page is copyrighted, and ";
message += "all content is protected.";
function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}
if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown = click;


Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.