Steps to extract viewmodel information from a specific controller following an ajax request

I am encountering an issue with passing updated data from my controller to the view after making an Ajax call. Here is a simplified version of what I am trying to achieve:

Javascript

$ANALYZE = $('#submitID');

$ANALYZE.click(function () {
    var objectID = document.getElementById('objectIDInput').value;

    $.ajax({
        url: '@Url.Action("AnalyzeData")',
        type: "POST",
        dataType: "json",
        data: { 'objectID': objectID },
        success: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
});

Controller

public ActionResult Index(AnalyzeViewModel data)
{
    //Logic to update view model
}

[HttpPost]
public ActionResult AnalyzeData (int objectID)
{
    //Logic to analyze data and update view model, then return JSON response
}

View

<tbody class="scrollContent">
    @if (Model.fileData != null)
    {
        //Display data in table
    }
</tbody>

Answer №1

Here is a sample code snippet that shows how to retrieve data in the success function of jQuery:

Jquery

$ANALYZE = $('#submitID');

    $ANALYZE.click(function () {
        var objectID = document.getElementById('objectIDInput').value;

        $.ajax({
            url: '@Url.Action("AnalyzeData")',
            type: "POST",
            dataType: "json",
            data: { 'objectID': objectID },
            success: function (data) {
               // Inside this block, 'data' represents the viewmodel
              // Add your logic here
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    });

Controller Method Code:

[HttpPost]
public ActionResult AnalyzeData (int objectID)
{
    List<string> retList = new List<string>();
    AnalyzeViewModel avm = new AnalyzeViewModel();

    try {
        retList = SOME LIST

        avm.fileData = retList.ToArray();

        Response.StatusCode = (int)HttpStatusCode.OK;
        var obj = new
        {
            success = true,
            responseText = "Zones data has been calculated."
        };


        return Json(avm, JsonRequestBehavior.AllowGet);
    }

I hope you find this information useful.

Thank you,

Karthik

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

Format numeric values to millions and thousands by rounding them off

I'm attempting to create a price format for display purposes, where I aim to show a number with the suffix of million (M) or thousand (K), with only up to 3 values displayed, always rounded down. I came across this question that is quite similar to w ...

Tips on configuring an HTTP client to manage the response for an HTTP DELETE request and its body

When sending DELETE requests with body content in .NET, I encountered an issue where the response always timed out. This problem occurred when using both WebClient and HttpClient to make the request. The API developers confirmed receiving the request on th ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Ways to conceal all components except for specific ones within a container using JQuery

My HTML structure is as follows: <div class="fieldset-wrapper"> <div data-index="one">...</div> <div data-index="two">...</div> <div data-index="three">...</div> < ...

Track the number of clicks on the pop-up registered in the PHPMyAdmin database

There seems to be an issue with the IP not appearing in the other table within the same database. On the page "recette1.php?id=1" <?php $bdd = new PDO('mysql:host=localhost;dbname=recettes', 'root', 'root'); include("C:/ ...

What are the steps to integrating an HTML source with jQuery Autocomplete?

Struggling with a challenging ajax call to an HTML source that is essential. The goal is to convert the html response into a format suitable for displaying in the jQuery autocomplete list. Working with Autocomplete and Ajax $("#From, #To, #FromVacation ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

What is the best way to handle multiple responses in Ajax within a single function?

Here is a simple code snippet: $.ajax({ url:'action.php', method: 'POST', data:{getcart:1}, success:function(response){ $('#getcart').html(response);//want to ...

Protractor: Decrease the magnification

Currently, I am working with protractor and facing the challenge of zooming out to 50%. Despite trying numerous solutions found on StackOverflow, none have successfully resolved the issue. Some attempted solutions include: browser.actions().keyDown(protra ...

Issue with Bootstrap 5 Carousel not transitioning between slides

I am trying to add a carousel to my webpage, but it seems like it's not sliding and only displaying the first image. I've double-checked my code and everything else from Bootstrap works fine. Here's the snippet of code I'm using: < ...

Utilizing CSS and jQuery to align images in the center of the screen

I'm attempting to display a larger image when hovering over a thumbnail using jQuery and CSS. I have two images like this <td> <% if camera["is_public"] == "t" %> <img src="https://media.evercam.io/v1/cameras/&l ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

Implementing Datatrans Ajax in Wordpress is a seamless process that enhances

I'm in the process of integrating a credit card payment service from datatrans.ch into my WordPress site. Datatrans provides an Ajax API, which you can access here: Datatrans Ajax API Example Code I copied and pasted the example code, saved it in a ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

What is the best way to retrieve the promise that encountered an error in the catch block while using async/await

I'm currently in the process of converting code that used .then/.catch to instead use async/await. One particular challenge I'm facing is how to access the original promise that fails within the catch block, for logging purposes. Here is the ori ...