部分視圖旨在用於可重複使用的視圖,將在整個網站的許多地方使用。
我覺得這非常有用,如果我們通過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