Struggling with sending intricate model to controller via ajax request

I've encountered an issue where my model is not updating properly when I click a button. Despite logging the data in the razor file and confirming that it's correct, the controller method receives an empty model.

Below is the onclick method being used:

function addCoupon() {
  var code = document.getElementById("coupon-entry").value;
  $.ajax({ // Validate coupon first. This is working.
    method: "post",
    url: `/cart/validate-coupon/` + code,
    contentType: "application/json; charset=utf-8"
  }).done(result => {
    if (result.success) {
      var model = @Html.Raw(Json.Serialize(Model));
      console.log(model); // Countries and CheckoutData are correct here
      $.ajax({
        method: "post",
        url: `/cart/add-coupon/` + code,
        contentType: "application/json; charset=utf-8",
        data: model
      }).done(result => {
        console.log("It worked");
      });
    }
  });
}

The model in question looks like this:

public bool IsPos { get; set; }
public List<CountryDto> Countries { get; set; }
public CheckoutData CheckoutData { get; set; }
public string Payment ProcessorError { get; set; }
public bool DisplayRequiredErrors { get; set; }
public List<string> ValidationErrors { get; set; } = new List<string>();
public PaymentInformationModel PaymentInformation { get; set; } = new PaymentInformationModel();
public bool UseSavedCard { get; set; }

This is the controller method currently being utilized:

[HttpPost("add-coupon/{code}")]
public async Task<IActionResult> AddCouponAsync(string code, CheckoutModel model)
{
  // Countries and CheckoutData are null here
}

I have researched similar issues on other platforms, however, the solutions provided did not resolve my problem. Any assistance would be appreciated.

Thank you!

Answer №1

To make it valid javascript, consider updating it to the following:

(Remember to enclose it in single quotes '')

var model = '@Html.Raw(Json.Serialize(Model))';

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

The GET request is returning a null array instead of the expected array contents

I am new to this, but I am trying to understand why my GET request is returning an empty array even though I am sure that the Mongo database collection is not empty. Each word form in the WordForm collection has a "lexicalform" key that refers to a Lexicon ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

Tips for converting a textbox value into a string:

When attempting to retrieve the textbox value in JSON format, I encountered an error while trying to include "+txtName.Text+". What is the correct format for writing the textbox value as a string? string json = @" { 'MemberName ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

Autofill with JavaScript - Dynamic Form Population

Looking to create a form-based HTML page. The objective is to have the second input box automatically populate based on the user's input in the first input box. I've gone through various guides and tried to implement this script, but it doesn&ap ...

Creating an axios URL using Vue data results in receiving the value of undefined

I'm currently experimenting with axios to retrieve data from openweathermap. I've been working on constructing the URL by utilizing various methods to extract latitude and longitude from the user's browser, followed by a function call to pie ...

Guide on showcasing an array in a table using DataTables in a single column

I find myself in a difficult situation because I am using DataTables for pagination and searching in an unconventional way. I have a table where I display vendor details such as names, emails, addresses, countries, and the materials they deal with. To fetc ...

Issue with Postgres connection pooling incompatibility with .NET core 6 Transaction scope

In my .NET 6 application, I am utilizing Npgsql and Dapper to connect to a Postgres database. Connection pooling is enabled in the Postgres connection settings. For reference, please visit this link. The issue arises when multiple commands are executed w ...

Having trouble with JQuery's .prop function not unchecking a checkbox?

I have been experimenting with different solutions in order to uncheck a checkbox when another checkbox is checked. Unfortunately, none of the methods I've tried seem to be working effectively... Currently, my code looks like this: $("#chkBox1").cli ...

Utilize jQuery.queue() to line up ajax requests in a queue

I'm having trouble understanding how to use jQuery.queue() for the first time. Can someone please help me figure out what I'm doing wrong? When I look in firebug, my POST requests still seem to be firing at the same time. I suspect that I might ...

How to Incorporate an Error Function into XPages Partial Refresh Events (dojo.xhrPost)?

I have a page that relies on multiple partial refreshes for user interaction. Rather than implementing a session keep alive mechanism, I am interested in detecting error responses from these partial refreshes to alert the user of their expired session or t ...

Component fails to update when state updated using useState()

In my current project, I am facing an issue with a parent (App) and child (MUIDatatable) component setup. The child component is a datatable that requires a columns prop to define the structure of the columns, including a custom render function for one of ...

Retrieving the identity value using Scope_identity() within a series of SQL client commands

Whenever I need to retrieve the correct scope_identity() value after inserting records, I typically resort to using a stored procedure. However, there's now a requirement for me to obtain the id field of an inserted record when utilizing SqlClient. M ...

Top method for filling an array with strings

Imagine having an array called 'newArray'. var newArray = []; You can add strings to it like this: var thisString = 'watch'; newArray.push(thisString); Now, if you want to have 50 instances of the 'thisString' in the newAr ...

Maintain the link's functionality even after it's been clicked by utilizing the same

I have a fixed navbar with same-page anchors and I want to keep the link active after it has been clicked and taken to that section of the page. While this is simple for links to another page, I'm struggling to figure out how to do it here. Here&apos ...

Retrieving distinct items from an array containing nested objects and sub-properties

In my script, I am attempting to retrieve unique objects based on the state from an array of objects. The current script is functioning correctly for most cases. However, there is one scenario where a nested object in a specific state has a sub-state, and ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

encountering problems with Next.js routing resulting in 404 errors

I developed a Next Js 14 app where I had to change the routing names inside the pages before going live. For example, instead of 'Charts', I changed it to 'charts' and made similar modifications to other pages as well. However, after de ...