I'm creating a 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. The user should be able to add new line item records to the viewmodel through an "Add" button, but the line items should not be committed to the database until the user clicks the "Save" button. Clicking the "Add" button should not refresh the page -- the page should stay exactly where it is, just with the extra rows added.
Right now, I have new rows being added in this way:
View:
@model Models.OrderViewModel
<table style="width: 90%; margin: auto" id="divPartial">
<tr>
<th style="width: 25px">
Header 1
</th>
<th style="width: 25px">
Header 2
</th>
<th style="width: 25px">
Header 3
</th>
</tr>
@if (Model.LineItemRows.Count > 0)
{
for (int i = 0; i < Model.LineItemRows.Count; i++)
{
@Html.Partial("ViewRow", Model.LineItemRows[i])
}
}
</table>
<input type="button" id="mybutton" value="Add New Line Item" class="btn btn-default" />
<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>
Controller:
[HttpPost]
public ActionResult AddNewLineItem(OrderViewModel viewModel)
{
OrderLineItemRowViewModel lineItemRow = new OrderLineItemRowViewModel();
// Set some defaults
lineItemRow.active = true;
lineItemRow.location = "I";
if (viewModel.LineItemRows != null) // This shouldn't ever be null
{
viewModel.LineItemRows.Add(lineItemRow);
}
return PartialView("ViewRow", lineItemRow);
}
When the user clicks on the "Add" button, a jQuery function serializes the current viewmodel and sends it back to the controller. The controller makes a new row with some default options, adds it to the viewmodel rowset that's passed in, then returns a partial view that represents the new row (and sends the data for the new row into the partial view so we know how to populate it).
The thing that's missing from this is...how do I send back the modified viewmodel to the original view? Basically, I've got what should be the current viewmodel in AddNewLineItem() but I have no idea where it needs to be sent.
I'm fairly new to ASP.NET MVC, so my apologies if I'm missing something obvious here.