我会为你刷新部分页面
第 1 步。 添加此类
public class JsonData
{
public string HtmlMsg { get; set; }
public string HtmlBody { get; set; }
public bool Success { get; set; }
}
步骤 2. 然后添加类 ViewHelper.cs
public static class ViewHelper
{
public static string RenderPartialToString(this ControllerBase controller)
{
return RenderViewToString(controller);
}
public static string RenderPartialToString(this ControllerBase controller, string partialViewName)
{
IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
return RenderViewToString(controller, view);
}
public static string RenderPartialToString(this ControllerBase controller, string partialViewName, object model)
{
IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
return RenderViewToString(controller, view, model);
}
}
第 3 步。 添加您的 PartialView 并将您要刷新的部分放入 PartialView 示例:_MyDiv
<div class="col-level1-20">
<div class="row-new shadow-slider-list background-white border-r-1-ddd border-t-ddd">
refresh div
</div>
</div>
第 4 步。您在控制器中的操作
public ActionResult areadetail(int id)
{
//............
return Json(new JsonData()
{
HtmlMsg = "OK",
HtmlBody = this.RenderPartialToString("_MyDiv"),
Success = true,
});
}
第 5 步。 在视图中添加 PartialView
@{
ViewBag.Title = "TestPartialView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section class="row-new margin-t-10">
<div class="row-new">
<div class="container style-direction-rtl">
<span class="style-font-16-sb color-black">Test PartialView</span>
</div>
<div class="container style-direction-rtl" id="yika">
@Html.Partial("_MyDiv")
</div>
</div>
</section>
第 6 步。 最后添加脚本
$(document).ready(function () {
var interval = 500;
var refresh = function () {
$.ajax({
url: "https://localhost:44399/area/areadetail/@ViewBag.i",
cache: false,
success: function (result) {
if(result.Success)
{
$('#yika').html(result.HtmlBody);
}
else
{
alert('failed');
}
}
error: function () {
alert('error');
}
});
};
});