.net MVC中如何使用iframe实现局部刷新

来源:互联网 发布:js清除input的value值 编辑:程序博客网 时间:2024/05/22 12:41

今天有人遇到在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" onclick="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>


其次,我们要在写button单击事件partRefresh()的js脚本,如下:

<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";)



原创粉丝点击