I'm still shaky with my use of ajax so there are a couple holes in my implementation here. I am trying to post to a controller action that will call a stored procedure to update my view model and then reload the div that will display the information.
Ajax Post:
$("#order-summary-panel").click(function(){
$.ajax({
url: '@Url.Action("GetOrderSummary", "Home")',
type: 'POST',
success: function() {
alert("It Worked!")
}
});
});
Controller Action:
[HttpPost]
public ActionResult GetOrderSummary
{
using (var entity = new OrderEntities())
{
var user = User.Identity.Name;
var orderSummary = entity.uspGetOrderSummary(user).ToList();
var viewModel = new OrderViewModel
{
OrderSummary = orderSummary
};
return View("Index", viewModel)
}
}
Div to reload:
<div id="order-summary-panel">
@if (Model != null && Model.OrderSummary != null)
{
foreach (var order in Model.OrderSummary)
{
// Display Orders
}
}
</div>
I believe that I shouldn't be returning the full view, but I am not sure how to update the view model without doing so. Any help would be appreciated.
You could return a PartialView and put the result in a div, for sample:
[HttpPost]
public ActionResult GetOrderSummary
{
using (var entity = new OrderEntities())
{
var user = User.Identity.Name;
var orderSummary = entity.uspGetOrderSummary(user).ToList();
var viewModel = new OrderViewModel
{
OrderSummary = orderSummary
};
return PartialView("Index", viewModel);
}
}
and in your javascript:
$("#order-summary-panel").click(function(){
$.ajax({
url: '@Url.Action("GetOrderSummary", "Home")',
type: 'POST',
success: function(data) {
if (data) { // check if data is defined
$("#order-summary-panel").html(data);
}
}
});
});
You also could try to return a json
an manipulate the html (which can improve the performance), for sample:
[HttpPost]
public ActionResult GetOrderSummary
{
using (var entity = new OrderEntities())
{
var user = User.Identity.Name;
var orderSummary = entity.uspGetOrderSummary(user).ToList();
var viewModel = new OrderViewModel
{
OrderSummary = orderSummary
};
return Json(new { success = true, order = viewModel }, JsonRequestBehavior.DenyGet);
}
}
And in your Javascript, you could try to read these properties:
$("#order-summary-panel").click(function(){
$.ajax({
url: '@Url.Action("GetOrderSummary", "Home")',
type: 'POST',
success: function(data) {
if (data) { // check if data is defined
if (data.success) { // if success is true
alert("It Worked!");
// you could read data.order
}
}
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With