asp.net-mvc 如何仅刷新 MVC 5 中索引页面的一部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21170064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh only part of the Index page in MVC 5?
提问by Ben Junior
The Index page contains two partial views. One is for the user to enter the search criteria, the other to show the results. How to update the data in the Results view only ?
索引页面包含两个部分视图。一种是让用户输入搜索条件,另一种是显示结果。如何仅更新结果视图中的数据?
I'm using MVC 5 and Razor. I've seen some examples on this, mostly using ajax and jquery. I'm asking what would be the best (prefer easier) solution for this
我正在使用 MVC 5 和 Razor。我已经看到了一些关于此的示例,主要使用 ajax 和 jquery。我在问什么是最好的(更简单的)解决方案
// INDEX VIEW:
// 索引视图:
<div id="div_Search">
@{Html.RenderPartial("~/Views/Shared/Search.cshtml", ViewBag.Model_Search );}
</div>
<div id="div_Results">
@{Html.RenderPartial("~/Views/Shared/Results.cshtml", ViewBag.Model_Results );}
</div>
// HOME CONTROLLER
public class HomeController: Controller { MainContextDB db = new MainContextDB();
公共类 HomeController: Controller { MainContextDB db = new MainContextDB();
public ActionResult Index()
{
// Code to initialize ViewBag.Model_Search, etc...
....
// Code to initialize ViewBag.Model_Results, etc... (Values empty at startup)
....
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetResults([Bind(Include = "DropOffLoc,DropOffDate,PickUpDate")] Search search)
{
// Retrieve results using the search parameters, etc...
....
// THIS RETURNS THE VIEW WITH THE DATA, BUT IN A SEPARATE PAGE (AS EXPECTED)
return View("~/Views/Shared/Results.cshtml", results);
// THIS RETURNS THE VIEW IN THE MAIN PAGE BUT WITH EMPTY DATA (AS EXPECTED)
return RedirectToAction("Index");
// HOW TO RETURN THE VIEW WITH THE DATA IN THE MAIN PAGE ?
???????
}
}
}
// THIS IS THE SEARCH PARTIAL VIEW
// 这是搜索部分视图
@model Models.Results
@using (Html.BeginForm("GetResults", "Home", FormMethod.Post, new { @class = "my-form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-group input-group-sm">
@Html.LabelFor(model => model.DropOffLoc)
@Html.DropDownListFor(model => model.DropOffLoc, ViewBag.LocationList as SelectList, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DropOffLoc)
</div>
<div class="form-group input-group-sm">
@Html.LabelFor(model => model.DropOffDate)
@Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
@Html.ValidationMessageFor(model => model.DropOffDate)
</div>
<div class="form-group input-group-sm">
@Html.LabelFor(model => model.PickUpDate)
@Html.TextBoxFor(model => model.PickUpDate, new { @class = "form-control datepicker", placeholder = "Enter Pick-up date here..." })
@Html.ValidationMessageFor(model => model.PickUpDate)
</div>
<div style="text-align: center; margin-top: 10px; margin-bottom: 10px;">
<input type="submit" id="getResults" value="GET RESULTS" class="btn btn-default btn-success" />
</div>
}
回答by SethMW
I would put a form in your search partial. Then have some action post that, via JQuery, to your GetResults Action, which should return:
我会在您的搜索部分中放置一个表格。然后通过 JQuery 将一些操作发布到您的 GetResults 操作,该操作应返回:
return PartialView("~/Views/Shared/Results.cshtml", results);
Then, in the success callback of your JQuery post, spit the returned results to your $("#div_Results") like so:
然后,在您的 JQuery 帖子的成功回调中,将返回的结果吐到您的 $("#div_Results") 中,如下所示:
$.ajax({
url: '/Home/GetResults',
type: "POST",
dataType: "html",
data: $("#FormId").serialize(),
success: function (data) {
//Fill div with results
$("#div_Results").html(data);
},
error: function () { alert('error'); }
});
Unless I have a typo or something, that should work. You'll need to replace the form selector with the Id of your form tag.
除非我有错别字或其他什么东西,否则应该可以。您需要将表单选择器替换为表单标签的 ID。
回答by Dev
though this question has an answer already, I thought I would post an alternative approach which would also work. This approach uses the same action method and only checks if the Request is an Ajax call which then only replaces part of the body. Here is the relevant code only.
尽管这个问题已经有了答案,但我想我会发布一种也可以使用的替代方法。这种方法使用相同的动作方法,只检查请求是否是 Ajax 调用,然后只替换主体的一部分。这里只是相关的代码。
//The search form
//搜索表单
@using (Ajax.BeginForm("Index", "Home",
new AjaxOptions()
{
HttpMethod = "GET", UpdateTargetId = "my-posts",
InsertionMode = InsertionMode.Replace
}))
{
<input type="text" name="term" placeholder="Search B.I & G" />
<input type="submit" value="" />
}
//Portion of the View
//部分视图
<section>
<div id="my-posts">
@Html.Partial("_Posts", Model.Posts)
</div>
Now here is the Index action method, if the Request is an AjaxRequest, it returns a Partial View which replaces contents of div with id my-posts. If the Request isn't an Ajax request then it loads the whole View.
现在这里是 Index action 方法,如果 Request 是 AjaxRequest,它返回一个 Partial View,它用 id my-posts 替换 div 的内容。如果请求不是 Ajax 请求,则它会加载整个视图。
public async Task<ActionResult> Index(string term)
{
var viewModel = new HomeFeedsViewModel();
viewModel.Posts = await Task.Run(() =>
db.Posts.Include("Comments")
.Include("By").OrderByDescending(o => o.PostedOn)
.ToList());
//Return a Partial View which replaces content on the View
//only if the Request is an Ajax Request
if (Request.IsAjaxRequest())
{
viewModel.Posts = viewModel.Posts
.Where(a => a.Title.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0
|| a.Message.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0
);
return PartialView("_Posts", viewModel.Posts);
}
return View(viewModel);
}
Hope this helps someone.
希望这可以帮助某人。
回答by tucaz
You will, in fact, need to use AJAX.
事实上,您将需要使用 AJAX。
The best approach, as I see, is to have a partial view and issue a AJAX Load (jQuery.load in jQuery) to it.
正如我所见,最好的方法是使用局部视图并向其发出 AJAX 加载(jQuery 中的 jQuery.load)。

