部分视图旨在用于可重复使用的视图,将在整个网站的许多地方使用。
我觉得这非常有用,如果我们通过ajax加载它。
以下是示例。这也将避免全屏刷新
_layout。CSHTML(或任何视图网页,其中将加载部分页面)
<div>
<h2>This is Partial View content</h2>
<div id="content"></div>
</div>
<script>
$(function() {
$("#content").html("Loading...");
setTimeout(function() { LoadPartialView(); }, 5000);
});
function LoadPartialView() {
$.ajax({
type: "GET",
url: '@Url.Action("GetPartialView", "Home")',
dataType: "html",
success: function (data) {
$("#content").empty();
$("#content").html(data);
$("#content").fadeIn('slow');
},
error: function (data) {
$("#content").empty();
}
});
};
</script>
模型
public class TestModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
控制器的动作
[HttpPost]
public PartialViewResult GetPartialView()
{
TestModel model = new TestModel();
model.Name="SomeName";
model.Address="Somewhere";
model.Age=25;
return PartialView("_PartialTestPage", model);
}
修订
为避免对部分视图进行硬编码访问,请使用将重定向到主视图的重载操作方法。像这样的东西。
[HttpGet]
[ActionName("MyOverloadedName")]
public ActionResult GetPartialView()
{
return RedirectToAction("Index", "Home"); //redirect to the main view
}
通过设置HttpGet/HttpPost,可以制作两个不同的同名动作方法。 看看这里更多的替代解决方案Can you overload controller methods in ASP.NET MVC?。
您目前如何刷新局部视图;通过AJAX请求? –
$('。menuLink')。click(function(){$('#configurationpanel')。load(this.href); return false;} – CloudAnywhere