Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading:

<div id="customerdetailsDIV" class="well main-well clearfix">
    @Html.Partial("_customer_details", Model.customerviewmodel)
</div>

The following excerpt showcases the structure of the partial view, with all data already bound. The model and URL are passed to a common.js file through the script:

@model myproject.Models.customerdetails

<div class="col-md-5ths plain-well">
    <label>Title:</label>
    @Html.TextBoxFor(x => x.title, new { @class = "form-control" })
</div>

// etc //

<div class="col-md-5ths plain-well">
    <div id="customerSaveBtn" class="btn btn-success btn-block">Save</div>
</div>

<script>
    var url = "@Url.Action("savecustomerdetails", "Home")";
    var model = @Html.Raw(Json.Encode(Model));
</script>

This next portion refers to the JavaScript code within my common.js file:

$("#customerSaveBtn").on("click", function () {
    $.ajax({
        type: "POST",
        data: JSON.stringify(model),
        url: url,
        contentType: "application/json"
    }).done(function (res) {
        $("#customerdetailsDIV").html(res);
    });
}); 

The data is then sent back to my controller using the following method:

[HttpPost]
public PartialViewResult savecustomerdetails([System.Web.Http.FromBody] customerdetails model)
    {
        mycontext db = new mycontext();
        CustomerDetail item = db.CustomerDetails.Where(x => x.CustomerID == model.customerID).FirstOrDefault();
        item.FirstName = model.forename;
        // etc //            
        db.SaveChanges();
        return PartialView("_customer_details", model);
    }

One issue I am encountering is that when setting a breakpoint in my controller, the passed model does not reflect any newly inputted data from the view, only showing the initial data. It seems like the binding process is not functioning correctly.

Additionally, if I manually assign a value to one of the text fields in the controller for testing purposes, the partial view does not refresh with the updated data.

EDIT:

I made adjustments to my code as suggested below:

<div id="customerdetailsDIV" class="well main-well clearfix">
    @using(Html.BeginForm()) {
        @Html.Partial("_customer_details", Model.customerviewmodel)
    }  
</div>

$("#customerSaveBtn").on("click", function () {        
    $.ajax({
        type: "POST",
        data: $("#customerdetailsDIV > form").serialize(),
        url: url,
        contentType: "application/json"
    }).done(function (res) {
        $("#customerdetailsDIV").html(res);
    });
});

Currently, my breakpoint is not triggered at all. Could this be because my controller is expecting a specific model?

Answer №1

To implement this functionality, first, create a form within the View and insert your div using the partial helper.

@using(Html.BeginForm()) {
   <div id="customerFormDIV" class="well main-well clearfix">
       @Html.Partial("_customer_details", Model.customerviewmodel)
   </div>
} 

Next, serialize the form data and send it via Ajax.

$("#customerSaveBtn").on("click", function () {
    $.ajax({
        type: "POST",
        data: $("#customerFormDIV").closest("form").serialize(),
        url: endpointURL,
        contentType: "application/json"
    }).done(function (response) {
        $("#customerFormDIV").html(response);
    });
}); 

Answer №2

After struggling to figure out a solution for a form, I eventually followed the advice given by @ramiramilu.

$("#customerSaveBtn").on("click", function () {
    var data = {
        customerID: $('#customerID').val(),
        title: $('#title').val(),
        forename: $('#forename').val(),
        surname: $('#surname').val(),
        address1: $('#address1').val(),
        address2: $('#address2').val(),
        address3: $('#address3').val(),
        address4: $('#address4').val(),
        postcode: $('#postcode').val(),
        email: $('#email').val(),
        contact: $('#contact').val()
    };

    $.ajax({
        type: "POST",
        data: JSON.stringify(data),
        url: url,
        contentType: "application/json"
    }).done(function (response) {
        $("#customerdetailsDIV").html(response);
    });
});

Following these steps resolved the issues mentioned in the original post.

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

Determining the parameter type for the directive

How can you specify the types of parameters for the directive in AngularJS? Which type should be used for & binding? Refer to ngdoc or jsdoc for an example code. UPDATE: I am looking for answers to the following questions * @param {<< What sh ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

Downloading a file using iron-ajax

Is there a way to download a file using Polymer's Iron-Ajax? <iron-ajax id="fileDownloader" headers='{"Auth" :"token"}' url="/my/server/rest/download/csv/{{id}}" method="GET" content-type="application/json" on-response="downl ...

Ensure to preselect the radio button based on the Day's value

I have set up my Radio buttons with corresponding content to be displayed when clicked. I want to automatically pre-select the tab button based on the current day. For example, if today is Sunday, the page should load showing the contents for Sunday. If i ...

Navigating a Mesh in 3D Space using three.js, Camera Movement, and physi.js

I am attempting to manipulate an object in Three.js using Physi.js. The camera is linked to the moving mesh, and I am moving it using .setLinearVelocity(); Additionally, I rotate it using .setAngularVelocity(); However, the issue I am facing is that whil ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

The onKeyUp event is not functioning as expected in React, unlike the onChange event

For a React coding challenge, I am required to update a value onKeyUp instead of onChange. However, after changing it to onKeyUp, my fields are not updating and I cannot type anything into the textarea. class MarkdownApp extends React.Component { constr ...

The data retrieved using Ionic 3 Angular Fire's payload.val() seems to be returning

Is it possible to determine whether a profile is filled in or empty when using Firebase Database for storing profile information? Currently, I am utilizing profile.payload.val(), but it seems to return null in both cases instead of true when the profile is ...

Disable a href link using Jquery after it has been clicked, then re-enable it after a

There are several <a target="_blank"> links on my website that trigger API calls. I want to prevent users from double clicking on these buttons. This is what I have tried: .disable { pointer-events: none; } $(document).ready(function(e) { ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

When a click event triggers, use the .get() method in jQuery to retrieve the content of a page and then update

I am currently facing an issue with a div class="contentBlock", which is acting as the container for updating content. <div class="contentBlock"></div> Unfortunately, the script I have written does not seem to be working properly :c $(docume ...

What is the best way to extract the text inside a div element based on the input value in a

I attempted to extract the innerText of a div along with the input values within it. For instance: <div> My name is Shubham, I work for <input type="text"/> for the last 5 years.</div> My objective is to retrieve all the text ...

Replace or update the current array of objects that align with the incoming array

I've been struggling to figure out how to find and replace an array that matches the existing one. The issue lies with using the some method. Here is the current array: let existingData = [{ id: 1, product: 'Soap', price: ' ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

The $http.get in AngularJS is causing a problem by returning undefined and $http() is not being recognized

I am currently working on an app that is designed to load and display data dynamically from a database using AngularJS. However, I have been encountering errors when trying to access my API using both $http() and $http.get(). The specific errors I am recei ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...