`Is there a clash between UpdatePanel and RegisterStartupScript?`

I am facing an issue with the client-side validation in my user control. Everything works fine when the user control is placed on a page, but if there is a postback event (like selecting an option from a dropdown that displays more fields), the validation stops working. Below is the code for my validation logic:

protected void Page_Load(object sender, EventArgs e)
{
    Type cstype = this.GetType();

    if (!Page.ClientScript.IsStartupScriptRegistered(cstype, "ValidatorType"))
    {
        String DateValidator;
        DateValidator = "<script type=\"text/javascript\">\n";
        DateValidator += "function ValidateDate(source, args) {\n";
        DateValidator += "   var ddDay = document.getElementById(source.day);\n";
        DateValidator += "   var day = ddDay.selectedIndex;";
        DateValidator += "   var ddMonth = document.getElementById(source.month);\n";
        DateValidator += "   var month = ddMonth.selectedIndex;\n";
        DateValidator += "   var ddYear = document.getElementById(source.year);\n";
        DateValidator += "   var year = ddYear.selectedIndex;\n";
        DateValidator += "   if (day == 0 || month == 0 || year == 0)\n";
        DateValidator += "      args.IsValid = false;\n";
        DateValidator += "   else\n";
        DateValidator += "      args.IsValid = true;\n";
        DateValidator += "   }\n";
        DateValidator += "</script>";
        Page.ClientScript.RegisterStartupScript(cstype, "ValidatorType", DateValidator);
    }
    Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "month", ddMonth.ClientID);
    Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "day", ddDay.ClientID);
    Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "year", ddYear.ClientID);
}

I need help figuring out why the validation fails during postback events.

EDIT:

Below is the code snippet of the User Control I am using:

<asp:DropDownList ID="ddMonth" runat="server" AppendDataBoundItems="true">
   <asp:ListItem Value="">--Month--</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddDay" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="">--Day--</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddYear" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="">--Year--</asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="reqDueDate" EnableClientScript="true" ClientValidationFunction="ValidateDate" runat="server" ErrorMessage="Required" CssClass="input-notification error png_bg" Display="Dynamic"></asp:CustomValidator>

Answer №1

After some trial and error, I discovered that I needed to make 2 adjustments in my user code. First, I needed to wrap an Update Panel around it, and then modify the following lines:

Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "day", ddDay.ClientID);

to

ScriptManager.RegisterExpandoAttribute(UpdatePanelDDD, reqDueDate.ClientID, "day", ddDay.ClientID, false);

Thank you to everyone for your assistance, and a special thanks to for providing helpful guidance.

Answer №2

Here is an example of how you can achieve a similar result:

<script type="text/javascript>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(HandleEndRequest);

var button = null;

function HandleEndRequest(sender, args) {
    button = document.getElementById('<%= YourButton.ClientID %>');
    button.onclick = ValidateDate;
};
</script>

Alternatively, you could also bind this functionality to the form submit event on the client side.

Note: The endRequest event is triggered when MS Ajax finishes any asynchronous request, such as updating the DOM with an UpdatePanel. More information can be found here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue.js: Creating a Custom Filter to Easily Filter Table Data

This table contains two columns: Name, and Age. Currently, the search functionality only filters by name. However, I would like to implement filtering by age using a comparison operator such as < or >. If you want to see the code in action, check ou ...

The controller's method is unable to retrieve input from the view page

I am facing an issue where the method is not receiving the id as expected. To debug this, I added console.writeLine(orderId); and it always shows 0 regardless of the object. Earlier, I encountered a similar problem which was resolved by adding an IActionR ...

What is the best way to utilize document.body in order to add a table to a designated DIV?

Once I make a copy of the table, my goal is to insert this new table into a designated DIV named div1. How can I add the new table to div1? <div id="div1"> </div> var copiedElement = document.getElementsByTagName("table" ...

Using jQuery to toggle visibility of various elements without needing specific identifiers

I have coded a HTML and JS snippet for displaying and hiding a div element, which is currently functioning correctly. However, I want to be able to use multiple boxes on a single page and I need a way to determine which box-header was clicked. Is there a ...

Ways to divide elements of an array into pairs

I am working with a javascript array containing values [A,B,C,D,E.....] that needs to be split using the following syntax: [ [A, B], [C, D], [E, F] ] This splitting process should always result in pairs. I attempted to achieve this using a loop to retur ...

Is it possible to transfer a massive number of files using node.js?

I need to asynchronously copy a large number of files, about 25000 in total. I am currently using the library found at this link: https://github.com/stephenmathieson/node-cp. Below is the code snippet I am using: for(var i = 0; i < 25000; i++ ...

Is there a method to give a webpage a subtle shimmering effect without utilizing CSS box-shadow?

Struggling to Develop a High-Performance Interface Feature I'm currently facing a challenge in coding an interface that requires a subtle and broad glow effect, similar to the example provided below: https://i.sstatic.net/E4ilD.jpg Exploration of ...

How can Node.js developers properly utilize PM2 for their projects?

I'm currently contemplating a switch from forever to PM2 as a way to ensure my node application stays up and running. I find myself puzzled by the various recommended methods for initiating a process: $ pm2 start app.js -i 4 # Daemonize pm2 and Star ...

Search for elements using XPath with multiple criteria, each on a separate line

I'm attempting to locate an element that contains text in two distinct places within the HTML code of a website. Apologies for my limited knowledge of HTML terminology. Here is a snippet of the HTML: <article> <div class="inner-article"& ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Sending a second request with jQuery to upload a file

After successfully uploading a file using jQuery AJAX along with a progress bar (XHR), the next step involves processing the uploaded file on the server side. To check the status of this server-side processing, I attempt to make another jQuery AJAX request ...

How should NodeJS be utilized for accessing various directories?

I'm currently working on a basic web application and I'm having trouble accessing different JavaScript files stored in a separate folder from the main one. To provide a clearer picture, here is my current file structure: myapp ├── clientSi ...

Combining Json attributes in Jquery Grouping

My task is to group the displays by sectors, but I couldn't find a method in JSON to achieve this. Below is the code snippet: $(function displays(){ var url = '{% url get_displays %}'; $.getJSON(url, function(data) { var sidebar = ...

Targeting a single element in a list with JavaScript operations

I'm facing a challenge with my current code (coffeescript) on Rails. I have a list of subscription videos being generated by Rails, and I want a popup to appear only when hovering over a specific video. However, every video in the list has the same cl ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

How to sort by a specific split part of an array using JavaScript and jQuery?

Looking to sort an array based on a specific split part of each element. example_array = ["Zebra:Add","Pay:Cold","And:Vets","Jam:Back"] The desired outcome is: console.log(code here) // prints ["Zebra:Add","Jam:Back","Pay:Cold","And:Vets"] Note: Each p ...

What is causing the issue with asp.net dynamic button not firing within a loop?

Encountered an intriguing challenge involving dynamically created buttons. Check out the method used to generate these buttons: private void CreateButtons() { // Button outside loop functions correctly Button selectItem = new Button(); select ...

What is the sequence of the middlewares for error handling and handling of 404 errors?

The express.js website has confused me with contradictory statements regarding error-handling middleware. According to one page, you should define error-handling middleware last, after other app.use() and routes calls. However, another page states that you ...

Utilizing an IPv6 address to establish a connection with a server through HttpClient (employing the IPv6 address to designate the URI) Resolving - Error: Invalid URI - Port specified

My HttpClient is functioning flawlessly when connecting via ipv4, fqdn, or host names (see code snippet below). However, I ran into an issue when attempting to use an ipv6 address to establish a connection with the server. It seems like I may need to adjus ...