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

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

UI-grid: Triggering a modal window from the filter header template

Is there a way to create a filter that functions as a simple modal window triggered by a click event, but can be displayed on top of a grid when placed within the filterHeaderTemplate? I have encountered an issue where the modal window I created is being ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Remove search results in real-time

I'm currently working on implementing a search feature for a web application. While I have made some progress, I am facing an issue with removing items when the user backspaces so that the displayed items match the current search query or if the searc ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

Utilize Javascript to interact with specific Objects

Working with Node.js, I have written a code that produces the following output: entries: [ { data: [Object] }, { data: [Object] }, { data: [Object] }, ... { data: [Object] } ] } null The code snippet is as follows: targetingIdea ...

Comparing NodeIntegration, Preload Script, and IPC in Electron Framework

After thoroughly going through Electron's explanations on context isolation, IPC, and security, as well as delving into discussions like this thread about nodeIntegration and this post regarding preload.js, it's clear that there are various appro ...

Implementing a click event on a selection option – tips and tricks

When I want to select an option, I can use the following script: Javascript $("#practice-area optgroup option").click(function(){ // insert your function here }); HTML <select name="practice-area" id="practice-area"> <option value="0">S ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Implement a mouseenter event to all input elements that have specific names stored in an array, utilizing jQuery

I'm struggling to figure out how to apply my function to all input elements with a name that is included in my array. This is what I've attempted so far: var names = ["name1", "name2"]; $(document).ready(function(){ $('input[name=names[ ...

Are there any libraries available to simplify HTML development in C#, .NET, or ASP.NET?

I have a vivid memory of stumbling upon a project where an individual utilized json-like strings to generate high-quality HTML in a certain programming language. Is there a similar tool available for use with C# or .NET? radio-box{ AName, [First|Second| ...

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

Executing PHP Functions with Script Tags

I am trying to use PHP to output the <script></script> tag. Here is the code I am using: <?php echo "test"; echo "<br>"; echo '<script src="http://mywwebiste./mycode.js" type="text/javascript& ...

Exploring the @HostBinding argument in Angular directives

Need help grasping the concept behind the @Hostbinding argument: Snippet of the code: import { Directive, HostBinding } from "@angular/core"; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding(&apos ...

The error "TypeError: b.toLowerCase is not a function in the bootstrap typeahead plugin" indicates that

Currently, I am working on implementing autocomplete search using the typeahead plugin version 3.1.1. My implementation involves PHP, MySQL, AJAX, and JavaScript/jQuery. While everything works perfectly with mysqli in terms of displaying suggestions when t ...

Arrange the Elements of Select Options

I am currently facing an issue with organizing the elements in my select list. I have two interconnected lists, one containing a list of "models" which I have successfully sorted using the following function: var sel = $('#model'); var opts_lis ...