Sending an AJAX request to a Controller Action using an Object as input

I am currently using an AJAX call to a Controller within an ASP.NET MVC solution. The code snippet for the AJAX call is as follows:

$.ajax({
        url: "ControllerClass/ControllerMethod?date=" + date,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            globalVariable = result; // This is for later...
            DoSomething(result);
        },
        async: true,
        processData: false
    })

After performing server-side operations, the controller returns an Object with various property types (an Int, an Array of Int, and a List of Objects).

The method I use to return this data back to the JavaScript file is...

return Json(new
{
   summary = objectResult
});

Now, I want to call a different Controller from the JavaScript with the information stored in my globalVariable.

var globalVariable

This variable is declared at the top of my JS file...

When trying to call the controller with that variable, here is how it looks:

$.ajax({
                url: "ControllerClass/ControllerMethod?result=" + globalVariable,
                type: "POST",
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    DoSomethingNewWithThisresult(result)
                },
                async: true,
                processData: false
            })

This is the C# controller method:

public IActionResult ControllerMethod(JsonResult result)
{
     DoSomethingHereWithTheResult(result);       
}

However, I am facing an issue where the result variable is empty when I set a breakpoint on the last controller. Checking in Chrome shows that the variable contains the expected data. Interestingly, if I pass just one property of the object, it works fine but passing the entire object doesn't work...

Answer №1

Consider creating your own custom model instead of relying on JsonResult as a parameter in the action and utilize it in an ajax call like this:

$.ajax({
            url: "ControllerClass/ControllerMethod",
            type: "POST",
            dataType: 'json',
            data: { Summary: globalVariable.summary},
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                PerformActionWithResult(result)
            }
        })


public class YourClass
{
    public string Summary { get; set;}//// string type or any other type
}

public IActionResult ControllerMethod(YourClass result)
{
     HandleResultHere(result);       
}

Alternatively, you can also utilize JSON.stringify to serialize your object in this manner:

var customObject={
"Summary" : globalVariable.summary
};

  $.ajax({
            url: "ControllerClass/ControllerMethod",
            type: "POST",
            dataType: 'json',
            data: JSON.stringify(customObject),
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                PerformActionWithResult(result)
            }
        })

Answer №2

To handle complex type parameters in a Web API controller, there are various approaches available - similar options also exist for MVC controllers.

If the parameters are included in the URL and directly map to your object's properties, you can use the [FromUri] attribute to easily bind them, as shown below:

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

public ValuesController : ApiController
{
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Another method is to utilize the IModelBinder interface along with the [ModelBinder] attribute for more control over creating and populating your object from the request.

By implementing the BindModel method in the IModelBinder interface, you can customize how your object is instantiated and populated using query parameters from the URL before it reaches your controller method:

A simplified example implementation could look like this:

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
   if (bindingContext.ModelType == typeof(MyComplexType))
   {
      MyComplexType model ;

      // Retrieve data from value provider or HttpRequest
      //var theValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
      //var theValue = request.RequestUri.ParseQueryString();
      
      if (new MyComplexTypeConverter().TryParse(actionContext.Request, out model))
      { 
         bindingContext.Model = model;
         return true;
      }
      else
      { 
         bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert request to MyComplexType");
         return false;
      }
   }

   return false;
}

For further information, please refer to the following documentation: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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

Modifying the color temperature or warmth in Three.js can enhance the visual aesthetics

In my three.js project, I've set up a room scene with various lights added to it. Features such as exposure, power, and height adjustments have been included in the setup. You can view the progress so far by visiting this link. My next goal is to i ...

There seems to be an issue with rendering or redirecting in Jade files, the routes folder, and server/app.js

//routes/meal.js var express = require('express'); var router = express.Router(); var app = express(); /* GET users listing. */ router.get('/meal', function(req, res, next) { res.render('/home/noah/Desktop/gadfit/views/meal.jad ...

Details of the full page will be displayed upon the successful execution of the AJAX call in CodeIgniter

I am currently learning how ajax functions in CodeIgniter. The issue I am encountering is this: In ajaxex.php, there is a div called 'ShowMember', where I intend to display member details after selecting a 'member id' from the dropdown ...

Tips for displaying an uploaded image using the Valums file uploader

I recently implemented the Andrew Valums File Uploader on my website and it's functioning as expected. I am now looking to modify it so that instead of displaying just the uploaded filename and size, it will show the uploaded picture directly in the b ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...

Sequential jQuery AJAX requests triggering in an incorrect sequence

One challenge I am facing involves a select list with bundles of short texts. Upon selecting a specific bundle, the texts are displayed in two tables. Each table row has a "Delete" icon to remove a text from the bundle. I am aiming to refresh both the tabl ...

Adding a .PHP File to Two Separate DIVs

I am using wordpress to create a custom theme. I'm interested in placing all the content from my slider.php file inside a div box on my index.php page. How would I go about doing this? SLIDER.PHP <div class="slider"> // All the image tags wit ...

Why is my website not appearing in Google search results when searching in Arabic?

When I search in Google using Arabic language, I am unable to find my website. In English, I can easily locate the site, but there seems to be an issue with Arabic language search results. I have tried implementing this code in my main layout and include ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

CORS (Cross-Origin Resource Sharing) Request Failed

Whenever I utilize axios to send a XMLHttpRequest, an error occurs. Error: XMLHttpRequest cannot load . The preflight request is unsuccessful because there is no 'Access-Control-Allow-Origin' header present on the requested resource. Hence, acce ...

Issue with jQuery selector when handling AJAX response

I've been scratching my head trying to understand why this code isn't functioning as expected. To make things clearer, I created a simplified version of the issue on jsFiddle, where it works perfectly. Here's what I'm trying to achieve ...

Utilizing One-to-Many Microphone Streaming Technology

I'm looking to create a unique one-to-many microphone streaming system where a user can record from their microphone and others can listen in. I also need to be able to record the microphone session. Would it be better to use WebRTC for client commun ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

Prevent content from occupying unnecessary space below a sticky div

When the "link" on the sticky header is clicked in this scenario, how can I ensure that the linked content item (#mypara) appears below the sticky div rather than directly underneath it where it may be hidden? $(document).ready(function() { $(window ...

Tips for utilizing the feathersjs filter service efficiently

Hey, I'm a bit confused about what the filter service is and how to use it. I recently updated my node, npm packages, and all node_modules. When creating a new service, I receive a new file that looks like this: /* eslint no-console: 1 */ console.war ...

The function get() in p5.js will provide you with an array of pixels that is empty

I am currently working on a project that is inspired by this particular video. Within p5.js, I have been utilizing the get() function. My goal is to divide a large tileset into smaller images and store them in an array. However, I have encountered an issue ...

Setting a Vue child component class directly from its parent component

In my Vue component, I have multiple child components that are inputs of the same type. The number of inputs can vary depending on the user, but there is a rule that at least one input must be filled. For example, there could be 5 inputs with 4 of them emp ...

Issue with Sequelize Associate function not functioning correctly

I've been attempting to connect two tables in Sequelize, but I keep encountering the SequelizeEagerLoadingError indicating that one table is not associated with the other, despite trying all the suggested solutions on this platform. The tables in que ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...