如何通过操作结果从另一个局部视图更新局部视图

我对主视图有三个部分视图 像这样的东西

在第一个局部视图中我有搜索function,当用户点击搜索时我想将结果刷新到第三个局部视图。

控制器:

public ActionResult Search() { virtualmodel vm = new virtualmodel(); return PartialView(svm); } [HttpPost] public ActionResult Search(ViewModel svm) { // Query to retrive the result // I am not sure what to return from here. Link to another action or just return back to same same partial } public ActionResult AnotherPartialPartial() { } 

在主要观点

  @{Html.RenderAction("Search", "Searchc"); } 

怎么做? 我需要ajax吗?

使用ajax,您可以调用控制器操作并将其响应返回给特定的div

div

 

Ajax在空div显示html:

 function performSearch(searchCriteria) { //get information to pass to controller var searchInformation = JSON.stringify(**your search information**); $.ajax({ url: '@Url.Action("Search", "ControllerName")',//controller name and action type: 'POST', data: { 'svm': searchInformation } //information for search }) .success(function (result) { $('#div3').html(result); //write returned partial view to empty div }) .error(function (xhr, status) { alert(status); }) } 

jQuery会帮助你! 尝试处理提交按钮onclick事件,如下所示:

 $("#yourButtonId").click(function() { $.ajax({ type: "POST", url: "/yourUrl", //in asp.net mvc using ActionResult data: data, dataType: 'html', success: function (result) { //Your result is here $("#yourContainerId").html(result); } }); }); 

你可以用ajax做到这一点。

首先,在视图中将html.beginform更改为ajax.beginform,并将div id添加到要更改内容的UpdateTargetId中。 使用ajax.beginform更新第一个partial后,可以使用ajax.beginform的“OnSuccess”函数更新其他partialview。 您必须添加更新function:

 @using (Ajax.BeginForm("YourAction", "YourController", new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" })) { /*your code*/ }  

然后在您的控制器中,返回一个局部视图以刷新您在UpdateTargetId值中输入ID的视图部分:

 public ActionResult YourControllerName(YourModelType model) { ...//your code return PartialView("_YourPartialViewName", YourViewModel); } 

注意:在使用ajax时,不要忘记在视图中添加对“jquery.unobtrusive-ajax.min.js”的引用。

所以,假设您有View with PartialView,必须通过按钮点击更新:

 
@{ Html.RenderAction("UpdatePoints");}

有一些方法可以做到这一点。 例如,您可以使用jQuery:

  

PostActionToUpdatePoints是具有[HttpPost]属性的Action,用于更新点

如果您在操作UpdatePoints()中使用逻辑来更新点,可能您忘记为其添加[HttpPost]属性:

 [HttpPost] public ActionResult UpdatePoints() { ViewBag.points = _Repository.Points; return PartialView("UpdatePoints"); }