Passing model data using MVC and ajax

I'm encountering an issue while attempting to send data back to my save method using ajax. I prefer this method because it allows me to reuse the form on multiple screens by rendering it as a partial page with the same save function.

The problem I'm facing is that when I use this approach, it sends the data back to my save function but the serialized JSON is created during page load and does not capture the updated values. I would like the updated values to be sent back via ajax without having to manually capture every field's value on the page.

Below is the current code I am using which successfully sends the original values from the model back to my save method:

$("#Save").click(function () {
    var form = $('#Form');

    if (form.valid()) {
        var data = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model))';

        $.ajax({
            url: "/Save",
            type: 'POST',
            data: JSON.stringify({ modelJson: data }),
            contentType: 'application/json',
            success: function (result) {
                SaveFade();
            }
        });
    }

    return false;
});

Answer №1

To begin, it is recommended to utilize the .done, .fail, and .always methods on Deferred instead of relying on the success method when working with jQuery's $.ajax functions. Additionally, avoid directly incorporating Razor methods within JavaScript code due to potential syntax errors caused by single quote characters ('). Instead, enclose this data in a hidden div element with an assigned id:

<div id="formData">@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model))</div>

In your JavaScript code, retrieve this data as follows:

var data = $('#formData').html();
. This approach also allows for separating your scripts into a distinct .js file.

To address your issue, ensure that you submit the actual form using AJAX to communicate with the controller method. Enclose all form fields within a form element with an assigned id:

@using(Html.BeginForm("Method", "Controller", FormMethod.Post, new { id = "myForm" }))
$("#Save").click(function () {
    var form = $('#Form');

    if (form.valid()) {
        var data = form.serialize();

        $.ajax({
            url: "/Save", 
            type: 'POST',
            data: data
        }).done(function (result) {
            SaveFade();
        });
     }

     return false;
 });

For a helpful tutorial on forms in ASP.NET MVC, refer to:

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 OnKeyDown function may encounter issues in IE9, whereas it functions properly in all other browsers

I am facing an issue with the onkeydown property in a JavaScript function that triggers an alert. While it works perfectly fine in Chrome and Firefox, it seems to be failing in Internet Explorer 9. The keydown, keyup, and keypressed events do not seem to w ...

Issues with Bootstrap 4 (possibly JQuery) - mobile menu navigation items are unresponsive

I've encountered an issue with my Bootstrap4 navbar on mobile screens where the links in the menu don't seem to work. Below is the code I used: <nav class="navbar navbar-expand-sm navbar-dark" style="background-color: #E2BA28"> < ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Is it possible for JQuery AJAX requests to activate Angular ng-click directives?

I've been working on a mobile application that uses a combination of JQuery and Angular. Every now and then, I encounter a strange bug. The Angular directives are implemented in a partial that is included through the ng-include directive: <ng-inc ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Preventing or deleting local cache when sending a canvas blob through AJAX requests

I am sending a canvas image to my server via AJAX using the following method: myCanvas.toBlob( function( blob ) { var fdata = new FormData( ); fdata.append( 'myFile', blob ); $.ajax( { url: 'http://myScript.foo', ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

In Javascript, async functions automatically halt all ongoing "threads" when a new function begins

I have a dilemma with multiple async functions that can be called by the user at any point in time. It is crucial for me to ensure that all previously executed functions (and any potential "threads" they may have initiated) are terminated when a new functi ...

In order to keep a div fixed at the top of the screen as you scroll, you can achieve this effect by utilizing CSS positioning. As the user scrolls down the page, the div

Can someone please help me figure out how to make a div element stay fixed on the screen as I scroll down the page? I've tried multiple solutions but nothing seems to be working. Any assistance would be greatly appreciated! I'm struggling with t ...

Tips for executing and triggering the same function concurrently from various `<LI>` elements

Is there a way to execute the same function concurrently from multiple <LI> elements using javascript or jQuery? I am looking to utilize the same function with varying parameters to create a tabbed browsing experience. I want multiple tabs to load a ...

What is the mechanism behind the setTimeout function as an asynchronous timer when we specify a specific duration?

Can you identify the coding instructor, possibly Net Ninja or Fireship, who explained that in asynchronous setTimeout, it promises to run after a minimum time of 1 second but may actually take longer (e.g. 1015 milliseconds or 1200 milliseconds)? What ha ...

Prevent event listeners from being triggered during the '$destroy' event. Error: $on function is undefined

As I attempt to halt all event listeners when the scope is destroyed, a certain error arises. The following error is displayed: TypeError: vm.$on is not a function; Even using vm.on(..) does not resolve the issue angular.module('app.layout&apo ...

Vue Router is failing to match a URL that contains numerous dynamic parameters

I've been working on adding a nested url to my routes and have encountered an issue with the last route in my code. Every other route seems to be functioning properly. I attempted to nest the urls using the children property, but it wasn't succe ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Change the CSS element if the current URL is not example.com/page1 or example.com/page2

When I apply the following JS code snippets, my output is incorrect or does not display at all. Below are the codes in question: if (location.href != "website.com/page1" || "website.com/page2") { element.style.backgroundColor='none'; ...

Discover the power of EJS embedded within HTML attributes!

There are two cases in which I am attempting to use an EJS tag within an HTML attribute. SITUATION 1: <input style="background-image: url(<%= img.URL %>)" /> SITUATION 2: <input onchange="handleCheckboxChange(<%= i ...

Debugging on the server side of Meteor application is crucial for

I am attempting to debug a Meteor app on Windows using node-inspector. I am following these steps: First, install node-inspector by running: npm install -g node-inspector Next, start Meteor in debug mode by running: NODE_OPTIONS='--debug' meteo ...

The key to subscribing only once to an element from AsyncSubject in the consumer pattern

When working with rxjs5, I encountered a situation where I needed to subscribe to an AsyncSubject multiple times, but only one subscriber should be able to receive the next() event. Any additional subscribers (if still active) should automatically receive ...

Is it possible to open a CSV file by clicking on a link in an HTML document using AngularJS?

Is it possible to open a CSV file using AngularJS if I know the absolute path? Additionally, is there a way to open it directly in Excel? I have been attempting this method: <a target="_self" ng-href="{{csv_link}}">download csv</a> However, t ...