今天有人遇到在MVC中局部刷新問題,可以防止整個也頁面進行刷新,出現抖動現象。
網頁中的佈局還是選用的是table佈局,其實DIV+CSS不是一樣的原理和操作過程,這裏只是示範怎麼進行局部刷新。
首先在VS新建一個MVC工程,保證運行正常。
接下來修改Home/Index視圖,如下:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
主頁
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%--<h2><%: ViewData["Message"] %></h2>--%>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr style="width: 1000px; height: 100px">
<td style="width:1000px" colspan="2">
</td>
</tr>
<tr style="height: 400px">
<td style="width: 200px">
<button id="btOne" οnclick="partRefresh()">click</button>
</td>
<td>
<iframe id="iframe1Id" name="I1" style="height: 370px; width: 860px" src="http://www.sina.com">
</iframe>
</td>
</tr>
</table>
</asp:Content>
<script type="text/javascript">
function partRefresh() {
// document.getElementById("iframe1Id").src = "http://www.baidu.com";
document.getElementById("iframe1Id").src = "/Home/Baidu";
}
</script>
這裏的就是腳本需要方隊位置,只要在標籤content中即可。
接下來我們看看JS腳本中的一行代碼:
document.getElementById("iframe1Id").src = "/Home/Baidu";
在這裏的src指定了網址,既可以是我們熟知的各種網站,如 http://www.baidu.com 也可以是我們項目中的視圖文件,如這裏的“/Home/Baidu”就是HomeController對應的視圖Baidu。下面是我的Baidu.aspx文件內容.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Baidu</title>
</head>
<body>
<div>
<iframe src="http://www.163.com" style="height: 421px; width: 1165px"></iframe>
</div>
</body>
</html>
至此,我們的工作完成了,能夠進行局部刷新了,下面是我的截圖:
頁面加載後的截圖:
下圖是在單擊按鈕(注對應的js文件中的是 document.getElementById("iframe1Id").src = "/Home/Baidu";)
下圖對應的單擊按鈕之後的截圖(注:js中對應的是document.getElementById("iframe1Id").src = "http://www.baidu.com";)