Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering:

  • 1) I am having difficulty displaying the text sent from my controller onto my view...

  • 2) When I select an option from my dropdown list, I would like to send three labels from my controller.

    If anyone knows how to address these problems, please help! :)

In My View

<div class="col-md-6 col-sm-6 col-xs-12">
    <label id="lblCargo"></label>
</div>

@section scripts{
    <script>
        $(document).ready(function () {

        $("#ddlEmpleado").change(function () {
            var selectedItemValue = $(this).find(":selected").val()

            $.ajax({
                cache: false,
                type: "GET",
                url: '@Url.Action("getLabels", "AsignarBien")',
                data: {
                    "id": selectedItemValue,
                },
                contentType: 'application/json; charset=utf-8',
                Success: function() {
                    $("#lblCargo").text(data);
                },
                error: function() {
                    alert("error");
                }
                }
            );
        });

    });
</script>
}

In My Controller, Meantime I Have This

public JsonResult getLabels(Guid id)
{
    var result = (from item in vempleados.GetAll().ToList()
        where item.IdEmpleado == id
        select item.Cargo).SingleOrDefault();

    return Json(result, JsonRequestBehavior.AllowGet);
}

Answer №1

Make these three adjustments for it to function correctly:

  1. success should be in lowercase letters.
  2. Include the data parameter inside the success function.
  3. Remove the comma (,) after selectedItemValue.

To properly structure your $.ajax call, follow this format:

$.ajax({
    cache: false,
    type: "GET",
    url: '@Url.Action("getLabels", "AsignarBien")',
    data: { "id": selectedItemValue},
    success: function (data) {
        $("#lblCargo").text(data);
    },
    error: function () {
        alert("error");
    }
});

NOTE: There is no need to specify contentType for the GET request, so you can remove that part entirely.

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

when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented: When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing to the ...

Issue with FusionCharts rendering correctly arises when the <base> tag is present in the HTML head section

Combining AngularJS and FusionCharts in my web application has led to a unique issue. The upcoming release of AngularJS v1.3.0 will require the presence of a <base> tag in the HTML head to resolve all relative links, regardless of the app's loca ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...

Using the clientWidth property in React

While I have a solid background in Javascript, I am relatively new to working with React. In my previous projects where I coded directly in javascript for the browser, I frequently used the following code snippet: width = document.getElementById('elem ...

What is the best way to show toast notifications for various selections in a dropdown menu?

I have a dropdown menu labeled "FavoriteFoods" that includes options such as "Pizza," "Sushi," "Burgers," and "Biryani." When one of these food choices is selected from the dropdown, I would like a toast pop-up to appear with the message "Great choice!" ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Is there a way to uncheck a checkbox by clicking on a link?

Just have a single checkbox for toggling: <label><input type="checkbox" name="myfield" id="myfield" />&nbsp;&nbsp;Enable Sound</label> Users can click on it to turn sound on the site. I'm looking for a way to uncheck the ch ...

Changing the index of an item in an array in React based on order number

Hey there, I'm a new Reactjs developer with a question. It might be simple, but I'm looking to learn the best practice or optimal way to change the index of a selected item in an array based on user input. Essentially, the user will provide a num ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Looking for a custom JavaScript color wheel with advanced features?

In search of a javascript color picker/wheel that allows users to easily select colors for our paint shop. Once the color is selected, it should automatically add the color value to the shopping cart. Our online store is operated using PrestaShop, so we ...

I am attempting to utilize diagram.highlightCollection in gojs to showcase nodes that do not meet a specific condition

I have a list of node IDs (keys) and I need to highlight those nodes. For empty nodes, the same condition works fine. For example: checkEmptyNodes() { const emptyNodes = []; const diagDetails = this.myserv.getDiagramData(); ...

Issue encountered when toggling flip switch in Jquery Mobile

I am trying to create a calculator for my app using Jquery Mobile, but I am facing an issue with the flip toggle switch. Here is my script: <script type="text/javascript"> function dosis() { $peso = $('#peso').get(0).value $dosis = ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Guide on efficiently transferring fetched data from a MySQL database to a php file in JSON format

Trying to retrieve data from a MySQL table and return it as JSON in a PHP file. Below is the code snippet used for connecting to MySQL and fetching data. How can I now convert this data into JSON format? <?php $username = "user"; $password = "* ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Retrieve all elements from an array using jQuery

How do I extract all the elements from the array outside of the function? $.each(Basepath.Templates, function(i){ templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, descri ...

Guide to showcasing an image on an HTML page using HTTP header

I have an HTML page with a basic layout that includes a single button. When this button is clicked, it needs to trigger an HTTP request to a specific URL while including an Accept header for GET requests. The response from the HTTP URL will vary depending ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...