更新PartialView mvc 4
安永! 如何使用模型中的数据刷新部分视图? 第一次,当页面加载它正常工作时,但不是当我从Action调用它时。 我创建的结构如下:
在我看来的任何地方:
@{ Html.RenderAction("UpdatePoints");}
我的PartialView“UpdatePoints”:
Your points are @ViewBag.points
在控制器我有:
public ActionResult UpdatePoints() { ViewBag.points = _Repository.Points; return PartialView("UpdatePoints"); }
谢谢你的帮助!
UPDATE
感谢你的帮助! 最后我按照你的建议使用JQuery / AJAX,使用模型传递参数。
所以,在JS中:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction); var points= $('#newpoints').val(); $element.find('PointsDiv').html("You have" + points+ " points");
在控制器中:
var model = _newPoints; return PartialView(model);
在视图中
@Html.Hidden("newpoints", Model)
所以,假设您有View with PartialView,必须通过按钮点击更新:
@{ Html.RenderAction("UpdatePoints");}
有一些方法可以做到这一点。 例如,您可以使用jQuery:
PostActionToUpdatePoints
是具有[HttpPost]
属性的Action
,用于更新点
如果您在操作UpdatePoints()中使用逻辑来更新点,可能您忘记为其添加[HttpPost]属性:
[HttpPost] public ActionResult UpdatePoints() { ViewBag.points = _Repository.Points; return PartialView("UpdatePoints"); }
你也可以试试这个。
$(document).ready(function () { var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))"; $("#PartialViewDivId").load(url); setInterval(function () { var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))"; $("#PartialViewDivId").load(url); }, 30000); //Refreshes every 30 seconds $.ajaxSetup({ cache: false }); //Turn off caching });
它进行初始调用以加载div,然后后续调用以30秒为间隔。
在控制器部分中,您可以更新对象并将对象传递到局部视图。
public class ControllerName: Controller { public ActionResult ActionName() { . . // code for update object . return PartialView("PartialViewName", updatedObject); } }
感谢你的帮助! 最后我按照你的建议使用JQuery / AJAX,使用模型传递参数。
所以,在JS中:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction); var points= $('#newpoints').val(); $element.find('PointsDiv').html("You have" + points+ " points");
在控制器中:
var model = _newPoints; return PartialView(model);
在视图中
@Html.Hidden("newpoints", Model)
控制器:
public ActionResult Refresh(string ID) { DetailsViewModel vm = new DetailsViewModel(); // Model vm.productDetails = _product.GetproductDetails(ID); /* "productDetails " is a property in "DetailsViewModel" "GetProductDetails" is a method in "Product" class "_product" is an interface of "Product" class */ return PartialView("_Details", vm); // Details is a partial view }
在yore索引页面中,您应该有刷新链接:
Refresh
此脚本也应该在您的索引页面中: