5,693,062 members and growing! (18,724 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate License: The Code Project Open License (CPOL)

JavaScript Validation in User Control

By santosh poojari

This article shows how to implement a JavaScript block in a UserControl.
VB, Javascript, HTML.NET 1.1, NT4, Win2K, WinXP, Windows, .NET, WebForms, ASP.NET, Visual Studio, VS.NET2003, Dev

Posted: 19 Oct 2005
Updated: 19 Oct 2005
Views: 52,779
Bookmarked: 14 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
8 votes for this Article.
Popularity: 2.26 Rating: 2.50 out of 5
1 vote, 12.5%
1
3 votes, 37.5%
2
1 vote, 12.5%
3
1 vote, 12.5%
4
2 votes, 25.0%
5

Introduction

I have been searching in the internet to find ways to call JavaScript validation code from a User Control, but failed to find any. Then one of my friends helped me out in doing the task. This article will help new learners and developers who come across the scenario which I had. In our user control there is a dropdownlist dynamically loaded with data. It happens that we require to set focus on the Submit button on the change handler of the dropdown and even want to put some validation into it. Once the user changes an option in the dropdownlist and press the Enter button, it should call the Submit button event handler function. This will become clear while I take you through the example.

Key Scenario

  • Create a Web Form: Main.aspx
  • Create a User Control: UserJs.ascx

Implementation of the User Control

We can create a User Control using VS.NET 2003 by selecting a new item in the Solution Explorer project view. On creating the User Control we add the following code in the code behind. On the page load, we register the JavaScript function so as to call it from the code behind.

        'Put user code to initialize the page here

        '<summary>

        'This function will check whether selected index is 0

        '</summary>

        Dim strScript1 As String = "< script language" & _
            "=JavaScript > function CodeBehindButtonJs() {"
        strScript1 += "if (document.forms[0]." & uCtrlId & _
           "_ddlItem.selectedIndex == 0){alert('Validation:" & _ 
           "Please Select Item');return false;};}"
        strScript1 += "<"
        strScript1 += "/"
        strScript1 += "script >"
        
        '<summary>

        'This function will set focus on submit 

        'button on dropdownlist change event.

        '</summary>

        Dim strScript2 As String = "< script language=" & _ 
            "JavaScript >  function CodeBehindDDlJs(me) {"
        strScript2 += "document.forms[0]." & uCtrlId & "_btnSubmit.focus();}"
    
        'Here you can achieve id's by passinf this pointer too.

        strScript2 += "alert('You selected '+ me.value)}"
        strScript2 += "<"
        strScript2 += "/"
        strScript2 += "script>"
        
        '<summary>

        'Register javascript block to server control event.

        '</summary>

        If (Not Page.IsStartupScriptRegistered("Startup1")) Then
            Page.RegisterStartupScript("Startup1", strScript1)
        End If
        If (Not Page.IsStartupScriptRegistered("Startup2")) Then
            Page.RegisterStartupScript("Startup2", strScript2)
        End If
        
        '<summary>

        'Call javascript function on controls event

        '</summary>

        ddlItem.Attributes.Add("onchange", "return CodeBehindDDlJs(this);")
        btnSubmit.Attributes.Add("onClick", "return CodeBehindButtonJs();")

If we View Source any aspx page having the User Control, we will find that the dropdownlist source will look like this:

<select name="UserJs1:ddlItem" id="UserJs1_ddlItem" 
        onchange="return CodeBehindDDlJs();" style="width:120px;" >

The dropdownlist ID in the above case is ddlItem in the User Control and "UserJs1_ddlItem" in Main.apsx. In order to trap HTML elements in the User Control we require to use document.form[0].elementId. So this element ID is to be known by the User Control. For this we define attributes in the User Control, which will be used in Main.aspx.

Public uCtrlId As String = ""

Implementation of Main.aspx

Now we create the Main.aspx. In Main.aspx drag and register the User Control. In the HTML part, include the following property as shown. This will set the value of the User Control ID and it will be retrieved in the User Control for JavaScript validation.

        <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <uc1:userJs id="UserJs1" runat="server" uCtrlId="UserJs1"> </uc1:userJs>
        </form>
    < /body>

We can see that our case was different. If we have to control any web control by itself like on a change event handler, we have to trap the selected index and then the above process won't be difficult. In such a case we have to pass the 'CodeBehindDDlJs(this)' pointer to the JavaScript function. This pointer is nothing but a pointer to the object. The case which I demonstrate is that a control action has impact on another control and in that case we are not having the ID of the other control in the User Control JavaScript. So we have to set a variable attribute to store the User Control ID. That will be document.form[0].usercontolId_ddlItem.selectedIndex. This is how things work. There might be a number of ways to achieve this. I found one and I liked to share it. Hope this will help.

Note: I tried to trap the LinkButton object using the above method but in the alert statement I always got it as 'undefined'.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

santosh poojari


He is a Team Lead currently working with a software company in India.He has overall 5.5 years of experience in .net technology. He is a B.E in computers from Mumbai University. His area of Interest is Microsoft Technology : Asp.Net,C#,Web services,SSIS,SSRS,Windows Workflow Foundation 3.0,State Machine Compiler,Regular Expression, Enterprise Library3.0,Spring.net,Design Patterns and Architecture Design.
He is MCPD-EA Certified.

He loves playing Cricket,Driving,Music and Drawing Sketches.
Occupation: Team Leader
Location: India India

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
Generalhow we use javascript validation of controle in user control page in .netmemberskumars.500:07 10 May '07  
GeneralWhat if you have two of the same type controls...memberZeroDefectMachine6:07 10 Jan '07  
Generalwhy for uCtrlId??memberRomaHagen6:13 6 Nov '06  
GeneralWhat if the user control is dynamically loaded?membersinanju21:31 26 Jan '06  
GeneralRe: What if the user control is dynamically loaded?memberRicardo Casquete4:16 22 Feb '06  
QuestionIsn't there another way?memberdrkwtkns10:29 26 Oct '05  
AnswerRe: Isn't there another way?memberRomaHagen6:21 6 Nov '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Oct 2005
Editor: Smitha Vijayan
Copyright 2005 by santosh poojari
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project