Passing model data from view to controller via ajax request

Upon receiving a model of type HistorySearch in my view, I am looking to resend this model to the controller using ajax:

$("#exportCsv").click(function () {
    // get model as json
    var searchData = '@Html.Raw(Json.Encode(@Model))';
    searchData = JSON.stringify({ 'search': searchData });

    $.ajax({
        //contentType: 'application/json; charset=utf-8',
        url: '@Url.Action("ExportToCsv", "BankCosts")',
        type: 'POST',  
        data: searchData,
        dataType: 'json',
        error: function (xhr) {
            alert('Error: ' + xhr.statusText);
        },
        async: true,
    });
});

However, there was an issue with the contentType that caused the passed model to become null in the controller.

In addition, here is how my controller is structured:

[HttpPost]
public void ExportToCsv(HistorySearch search)
{
    // search properties are not filled. They are set to default value
}

It seems that the binding is not functioning correctly as the received search properties are being set to default values. Can you identify the issue?

Answer №1

By using

JSON.stringify({ 'search': searchData })
, you are converting your object into a string, which will be passed to the ActionResult as a string instead of an object. To fix this, remove the JSON.stringify and modify your ajax call like so:

$.ajax({url: '...', ..., data: { searchData }, ...

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

How to Implement Recursive Function Calls in JavaScript?

My goal is to create an interactive function using HTML and jQuery. I am utilizing jQuery to update and change attributes and text for a more seamless experience without page reloads, especially since it's not image-heavy. I have structured "scenes" ...

How to dynamically disable a dropdown based on the selection of another dropdown using AngularJS

This project has been more challenging than I anticipated. I thought it would be a simple task to accomplish. Currently, I am developing a basic form with an input text field and two dropdown boxes. These dropdown boxes represent different types of contra ...

Utilizing Three.js in your HTML code

Currently, I am using c9.io as my IDE to write and test code for a website. Despite my efforts to import the code outside of c9.io, it is still not functioning properly. (I am confident that the issue is not with the three.js script itself.) My HTML code c ...

Function for swapping out the alert message

I am searching for a way to create my own custom alert without interfering with the rendering or state of components that are currently using the default window.alert(). Currently working with React 15.x. function injectDialogComponent(message: string){ ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

How can I modify the appearance and behavior of an HTML button?

I simply need to update the button class and value in order to change the button's functionality. After successfully changing the value and class, the functionality remains the same as the old class. Why is this happening? Could it be that the brows ...

Reset preview image upon submission

I have a contact form where I am using the following code to display an uploaded image preview: [file fileuploader filetypes:jpg id:uploader] <img id="preview" src="#" /> <script> var uploader = document.getElementById(&apos ...

The type '{ }' does not include the properties 'params', 'isExact', 'path', 'url' from the 'match<Identifiable>' type

Currently, I am utilizing react router and typescript in order to extract the id variable from a route for use in a component. However, typescript is raising an issue: The type '{}' lacks the following properties found in type 'match' ...

Is it possible to transform an array into an object and retrieve the data using ajax and json?

When looking at the coding from a PHP page, we see: user_list.php: $myarray=array(); $myjson = json_encode($myarray); echo $myuser->searchUser($myjson); The resulting HTML is: [{"userID":"1","username":"\u9ec3\u9ec3&bso ...

Issues arise when JQuery functions fail to execute

This unique program showcases a series of error messages that are designed to appear under specific conditions. These conditions are identified through PHP code, following which the essential JQuery script is echoed via PHP to display the messages. Initia ...

What is the best way to incorporate unique body CSS for various pages within a ReactJS application?

I am currently in the process of developing a multi-page website and faced with the challenge of applying different CSS styles to the body based on the specific page. My approach involves using react-router-dom for handling routing, and my file structure ...

An exception has occurred in the format

I have a function that looks like this /// /// This function is used to populate the emplist drop down for mentor users. /// private void BindEmpDropDownForMentor() { string strSelectMentorQuery = "SELECT FIRST_NAME + ...

Utilizing Next.js - Implementation of a unique useThemeMode hook to efficiently manage theme preferences stored in the browser's localStorage, seamlessly integrating with toggleTheme

For a while now, I've been trying to figure out how to toggle my favicon based on the theme logic of my application and the current theme state stored in localStorage. My approach involves using CSS variables and data attributes applied to the html bo ...

"We are unable to set a value for a global array unless we utilize the .push() method

It's puzzling that I can't populate a global array without using the .push() method. (function() { var globalEmail = []; var testUpdate = function() { var arr = [1, 2, 3]; if (globalEmail.length > 1) { gl ...

How should I proceed if I encounter an npm error stating that cb() was never called?

Hey everyone. I keep encountering an issue with npm whenever I attempt to install packages. I am receiving the following error message: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <h ...

Issue with Material UI React JS Select component: Unable to deselect multiple values when more than one item is selected

Implementing a multiselect dropdown in material ui with specific conditions: The dropdown will contain [0 Apples, 1 Oranges, 2 Grapes]. By default, 0 Apples should be selected. None of the options can be unselected. If 0 Apples is selected and the user se ...

The SQL query fails to execute when triggered by window.location.href

Whenever a selection is made, I trigger a Javascript code using the onchange function. I pass along 2 parameters: //capaciteit.php function testfunction(week, id) { window.location.href = "capaciteitberekening.php?week=" + week + "&id=" + id; } The f ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

Basic AJAX PHP script

I have 2 scripts, submit.php and display.php. My goal is to render submit.php, click the submit button, and have the result div show the number 123. Currently, when I try this, my page just reloads. I'm not seeing any output in the Console so I&apos ...