问题描述
我对使用Ajax仍然感到不满意,因此我的实现中有几个漏洞.我试图发布到控制器操作,该操作将调用存储过程来更新我的视图模型,然后重新加载将显示信息的div.
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:
Ajax Post:
$("#order-summary-panel").click(function(){
$.ajax({
url: '@Url.Action("GetOrderSummary", "Home")',
type: 'POST',
success: function() {
alert("It Worked!")
}
});
});
控制器操作:
[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:
<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.
推荐答案
您可以返回PartialView并将结果放入div中,作为示例:
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);
}
}
并在您的JavaScript中:
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);
}
}
});
});
Json
对于示例,您也可以尝试返回 json
来操纵html(可以提高性能)
Json
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);
}
}
在Javascript中,您可以尝试读取以下属性:
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
}
}
}
});
});
这篇关于Ajax POST到控制器操作以更新视图模型,然后重新加载div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!