I'm creating an ASP.NET MVC 5 SQL Server (Entity Framework, database-first) application where there is an order record and a set of line item records attached to it. I am using viewmodels to display the data. The user can add new line item records to the viewmodel through an "Add" button, but the line items are not committed to the database until the user clicks the "Save" button. (I've previously written about the application regarding a different issue: ASP.NET MVC - passing modified viewmodel from AJAX to view)
I have the "Add" button working fine... except for one very important use case. If the user changes some data in the web page then presses the "Add" button, none of the changes to the web page data are sent when the @Html.Raw(Json.Encode(Model))
line is called:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#mybutton").click(function () {
$.ajax({
url: "../AddNewLineItem/",
cache: false,
type: "POST",
data: {
'viewModel': @Html.Raw(Json.Encode(Model)),
},
success: function (data) {
$('#divPartial').append(data);
},
error: function (reponse) {
alert("Error: " + reponse);
}
});
});
});
</script>
Obviously, the reason why this is happening is because the model has not been updated with the latest data from the web page. However, how do I force the model to be updated before shipping it off via JSON? (Alternately, is there some way to always keep the viewmodel in sync with what the user has typed in the form?)