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

Attempting to insert anchor links pointing from external pages to my mvc hyperlink

Here is the link on our company's ASP.NET-MVC site: @Html.ActionLink("OPIE Administrative & Compliance Track", "Index", "OPIECon") Since I am new to MVC, I have been struggling to find answers on my own. Currently, the link directs me to the OPIECon ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

Showcase images from a MongoDb database in an HTML document

Currently, I am utilizing Node.js with mongoose and EJS as the view engine. I have successfully created a simple send command to retrieve and send images on the server side by following these helpful guides: Setup file uploading in an Express.js applicat ...

Configure the input to accept integer values

This page that I have developed is designed for entering Latitude and Longitude values. <div class="container "> <form class="entry"> <div class="aligncenter"> <h5 style="color:MediumTurquoise; font ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

Utilizing Node.js createReadStream for Asynchronous File Reading

For a specific project, I developed a module that is responsible for splitting files based on the '\r\n' delimiter and then sending each line to an event listener in app.js. Below is a snippet of the code from this module. var fs = req ...

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

Is there a CSS rule that can alter the appearance of links once they have been clicked on a different webpage?

Just starting out here. Imagine I have 4 distinct links leading to the same webpage - is there a way to modify the properties of the destination page depending on which link was clicked? For instance, clicking on link1 changes the background color of the d ...

Error message: "In Jade and Express.js, the attribute req.body.[name of form] is not defined

I am encountering an issue while trying to update a database using a drop-down form. The problem is that req.body.[name of form] is coming up as undefined. Upon checking the console, I found that req.body shows up as an empty object {}. Below is the code ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

Failure of ConfirmButtonExtender to function properly when dynamically added to control collection

I've been attempting to dynamically add a ConfirmButtonExtender to my controls collection within a custom control during runtime. However, I can't seem to get the extender to wire to the button being added to the controls collection in the Create ...

What is the proper way to activate speech recognition on electron?

I have a chatbot application running on Electron, and I am in need of implementing speech-to-text functionality. I initially tried using window.SpeechRecognition and window.webkitSpeechRecognition, but it seems like Chrome does not support speech recogniti ...

Creating UV coordinates in THREE.js

I've been working on bringing a model into a scene using the OBJ loader in THREE.js. Initially, I had no issues importing the geometry and visualizing it with MeshNormalMaterial. However, as soon as I tried to use textures that require UV coordinates ...

AngularJS parent selector nearest to the element

I have successfully implemented a code to close a custom popup using jQuery, but I am looking for a solution that utilizes AngularJS instead of jQuery. Can anyone assist me in finding the equivalent of this.closest() in AngularJS? I aim to hide .popOverla ...

Enabling Cross-Origin Resource Sharing (CORS) with Javascript on the client side during

Currently, I am attempting to incorporate another website's login verification system into my own site. Although the code below is successfully retrieving the correct response ID, I am encountering CORS errors preventing the completion of the login pr ...

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...