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?