I have a main view that loads a partial view of data. This is the code used on initial load:
<div id="customerdetailsDIV" class="well main-well clearfix">
@Html.Partial("_customer_details", Model.customerviewmodel)
</div>
this is the partial view the following is a sample, but all data is bound. The script passes the model and url to my common.js file:
@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>
the following is my javascript in my common.js:
$("#customerSaveBtn").on("click", function () {
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#customerdetailsDIV").html(res);
});
});
this posts back to my controller:
[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);
}
The problem I have is that if i set a break point in the controller the passed model does not contain the newly typed data from the view, but only the initial data, so the binding does not seem to be working.
The second problem is that if I manually set one of the text fields in the controller to test the partial does not refresh with the new data.
EDIT:
I have changed my code based on the answer
<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);
});
});
My break point isn't being hit at all. Is it because my controller is expecting my model?
var model = @Html.Raw(Json.Encode(Model));you are using only input model, but not updating it on client side. so POST will send the initial model. You have to use JQuery to update themodelon client side before posting it to server.modelto any properties.