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

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

JavaScript refuses to connect with HTML

Just starting out in the world of programming, I decided to dive into a Programming Foundations class on Lynda.com. However, after following along for fifteen minutes, I encountered an issue - I couldn't seem to connect my JavaScript file to my HTML f ...

"Seeking clarification on submitting forms using JQuery - a straightforward query

My goal is to trigger a form submission when the page reloads. Here's what I have so far: $('form').submit(function() { $(window).unbind("beforeunload"); }); $(window).bind("beforeunload", function() { $('#disconnectform&apo ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

What steps can be taken to obtain the fully computed HTML rather than the source HTML?

Is there a way to access the final computed HTML of a webpage that heavily relies on javascript to generate its content, rather than just the source HTML? For example, if a page contains script functions that dynamically generate HTML, viewing the page sou ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Send a JSON object to a web server

I'm facing an issue while trying to post my JavaScript object to the server (using asp.net 4.5 c#). The user creates the object (with jquery) and then should be able to send it to the server for processing. The data that needs to be sent to the serv ...

Can a subclass be passed as a formal parameter in an overridden function and still successfully compile?

What is the optimal method for creating a mechanism in which a base class can contain a function with a class parameter, and a child class can replace the function with a parameter that is a subclass of the base class parameter? To clarify, I will outline ...

Merge the elements of one array with the elements of another array simultaneously

Can a function be created that combines each value from two arrays, even if the arrays are of different lengths? For example: arr1 = ["apple", "banana", "cherry"]; arr2 = ["pear", "kiwi", "orange"] mergedArr= ["applepear", "applekiwi", "appleorange", " ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

Issues with LinQ font sizing on display devices

Hey, I'm currently using LINQ to create a tag cloud based on the tags stored in my database. However, I've run into an issue that's been giving me some trouble. Whenever I add a new tag for the first time, it appears in the largest font size ...

Issues arise with the Node EJS module due to the malfunction of the include

Struggling with incorporating HTML snippets into my index.html, even after reviewing the EJS documentation. Directory Structure: project -public --assets ---css ---images ---js --Index ---index.html + index.css and index.js --someOtherPageFolder -views - ...

Ways to transform epoch timestamp to present timestamp?

Is there a way to accurately convert an epoch timestamp in milliseconds to the current timestamp in milliseconds? My Attempt: var currentTime = (resp.timestamp * 1000) + 1980000000; resp.timestamp represents the epoch timestamp I attempted to add 5 ho ...

Unlocking the Secrets of Timer Arrays in C#

I'm trying to set up a timer for each dataValue in _dataValues, which are stored in an array. For example, I want to create timers like timer[0]=timer0, timer[1]=timer1, timer[2]=timer2, and so on. This is the code I have so far: Timer[] timer = new T ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

Tips for designing a horseshoe-inspired meter using CSS

  I want to create a horseshoe-shaped gauge using CSS that resembles the image below:     My attempt involved creating a circle and cutting off the bottom, similar to the technique demonstrated in this fiddle: http://jsfiddle.net/Fz3Ln/12/   Here& ...