How to send data from JavaScript to ASP.NET

  $(document).ready(function () {
    $("#MainContent_ddlFieldName").on("change", function () {
                 var id = $(this).val();
                 var name = $(this + "option:selected").text();

                 $('#<%= lblValue.ClientID %>').text(name);
                 $('#<%= lblType.ClientID %>').text(id);
             });
         });


<asp:Label ID="lblValue" runat="server" Text="" Visible="true"></asp:Label>
 <asp:Label ID="lblType" runat="server" Text="" Visible="true"></asp:Label>



protected void btnSearch_Click(object sender, EventArgs e)
        {
             string strValue = lblValue.Text;
             string strType = lblType.Text;
        }

I am incorporating JavaScript and Asp.Net to extract the dropdownlist value and place it into a label. Even though it displays the text on the label, when I trigger a button or event, it reverts back to its previous value which is ""

If anyone could offer assistance with this, it would be greatly appreciated.

Thank you!

Answer №1

Consider utilizing a hidden field

aspx page

<asp:HiddenField ID="hType" runat="server" ViewStateMode="Enabled" Value="" />
<asp:HiddenField ID="hValue" runat="server" ViewStateMode="Enabled" Value="" />
<asp:Label ID="lblValue" runat="server" Text="" Visible="true"></asp:Label>
<asp:Label ID="lblType" runat="server" Text="" Visible="true"></asp:Label>
<asp:Button Text="text" OnClick="btnSearch_Click" runat="server" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#MainContent_ddlFieldName").live("change", function () {
            var id = $(this).val();
            var name = $(this + "option:selected").text();

            $('#<%= lblValue.ClientID %>').text(name);
            $('#<%= hValue.ClientID %>').val(name);
            $('#<%= lblType.ClientID %>').text(id);
            $('#<%= hType.ClientID %>').val(id);
        });
    });
</script>

code behind

    protected void btnSearch_Click(object sender, EventArgs e)
    { 
        //back-end code
        string strValue = hValue.Value;
        string strType = hType.Value;


    }

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

Exploring the beauty of semicolons within ES6

In my understanding, semicolons were supposed to be outdated with the introduction of ES6. However, I stumbled upon this today: Doesn't seem to work as expected: let i = 0 [0, 1, 2, 3, 4, 5, 6].forEach(item => console.log(item)) But it works wh ...

Utilize the Vue-Chartjs plugin registration for a specific chart component only

I am currently working with a chart component in Vue 3 using the composition API. My goal is to incorporate the datalabels plugin into this specific chart only. Upon attempting to register the plugin outside of the chart's data or options, I noticed ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...

What is the jQuery syntax for targeting a specific element within an object?

Is there a way to access a sub element from $(this)? For instance, how can I specifically select a span element inside the this object? ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Effects of jQuery Show / Hide on adjacent select box operations

I created a pair of select boxes where the visibility of one is controlled by the other. Initially, the controlled select box (#select02) works perfectly on page load as long as I don't show/hide it by selecting options in the controlling select box ( ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Can I use a custom font in an HTML5 canvas?

Has anyone had success importing a custom font for use in HTML5 canvas? I've been trying to do this by loading the font file on my computer, but all my attempts have failed so far. The canvas keeps showing the default font instead of the one I want to ...

Determine if the user's request to my website is made through a URL visit or a script src/link href request

Presently, I am working on developing a custom tool similar to Rawgit, as a backup in case Rawgit goes down. Below is the PHP code I have created: <?php $urlquery = $_SERVER['QUERY_STRING']; $fullurl = 'http://' . $_SERVER['SE ...

The div within the button is failing to properly adjust to height settings

Check out this Fiddle I'm currently working on a social thumbs up button and I've encountered some challenges. In my button design, I have included a second div to accommodate the right side of it. However, despite trying to adjust its height us ...

How to delete a line from a file in Node.js without modifying the buffer variable

Hello everyone, I am just starting to explore the world of Nodejs Recently, I created a function that reads data from a file, saves it in an array variable, and then makes some changes to this variable before writing it back to the file. The code snippet ...

Enhancing PHP function speed through pre-compilation with Ajax

I am curious about compiling server side functions in PHP with Ajax, specifically when multiple asynchronous calls are made to the same server side script. Let's consider a PHP script called "msg.php": <?php function msg(){ $list1 = "hello world ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Having difficulty transforming a JSON string into a JSON object using Javascript

Currently, I am working on a hybrid mobile application using Angular. I have a string that is obtained from a $http.jsonp request and I am attempting to convert the response into JSON format. After checking the validity of the JSON at , it appears to be va ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Accessing a webpage by directly pasting the URL into the address bar is functioning properly, but is

I'm facing an issue with accessing files from a vendor's application. When I directly enter the endpoints into the browser's address bar, the file opens up without any problems. However, when I try to access them using jQuery AJAX, I receive ...

Unable to access API endpoint for retrieving items as described in the Express/React tutorial on Pluralsight

Currently, I am going through a tutorial on React, Express, and FLUX. Unfortunately, I have encountered a roadblock in the form of a CANNOT GET error when trying to access my API data. https://i.stack.imgur.com/RbUzf.png In the server file under Routes > ...