Home  >  Article  >  Backend Development  >  Detailed introduction to ASP.NET MVC--View

Detailed introduction to ASP.NET MVC--View

零下一度
零下一度Original
2017-05-20 13:34:392463browse

Understanding Views

ASP.NET MVCUnlike ASP.NET or Dynamic Server Pages (ASP), it does not have anything directly corresponding to a page thing. In an ASP.NET MVC application, there is no page on disk that corresponds to the URL path you enter in the browser address bar. In an ASP.NET MVC application, the closest thing to a page is something called a view. In an ASP.NET MVC application, incoming browser requests are mapped to controller actions. A controller action may return a view. However, a controller action may perform some type of action, such as redirecting you to another controller action.

Code Listing 1 contains a simple controller called HomeController. HomeController exposes two controller actions called index() and details().

代码清单1 - HomeController.cs
使用系统; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Web; 使用 System.Web.Mvc; 命名空间 MvcApp.Controllers{     [HandleError]     public class HomeController:Controller     {          public ActionResult Index()          {               return View();           }          public ActionResult Details()          {               return RedirectToAction( “Index”);           }     }}

You can call the first action, the index() action, by entering the following URL in the browser's address bar:

/首页/index

You can The second action, the details() action, is called by entering this address in the browser:

/Homepage/Details

The index() action returns a view. Most actions you create will return a view, however, actions can return any type of action result. For example, the details() action returns a RedirectToActionResult, which can redirect incoming requests to the index() action.

The index() action contains the following line of code:

return View();

This line of code returns a view, and the path of the view on the server must be Same as the following path: Index.aspx

\View\Home\\

The path to the view is inferred from the names of the controller and controller actions.

If you wish, you can explicitly specify the view. The following line of code returns a view named "Fred":

Return View("Fred");

When this line of code is executed, a view will be returned from the following path:

\View\Home\Fred.aspx

2. Create a view

You can right-click on the folder in the solution browser and select the menu item "Add", "New Project" (Figure 1). Select the "MVC View Page" template to add standard views to your project.

01 (1).pngYou should be aware that you cannot add views to your project at will like you can in ASP.NET or ASP applications. You have to add the view to a folder with the same name as the controller (without the controller suffix) For example, if you want to create a new view called index, the view can be created by A controller named ProductController is returned, then you must add this view to the following folder of the project:

\View\Product\Index.aspx

The folder containing the view The name must correspond to the name of the controller that returns the view.

3. Add content to the view

A view is a standard (X)

HTML document

that can contain scripts. You use scripts to add dynamic content to views. For example, the view in Listing 2 displays the current date and time.

Code Listing 2 - \Views\Home\Index.aspx

<%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Index.aspx.cs”Inherits =“MvcApp.Views.Home.Index”%> 
<!DOCTYPE html PUBLIC“ - // W3C // DTD XHTML 1.0 Transitional // EN“”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“> 
 
     <头RUNAT = “服务器”> 
          索引</ TITLE> 
     </ HEAD> 
     <BODY> 
          <DIV> 
               的当前日期和时间是:
               <%回复于(DateTime.Now);%> 
          </ DIV> 
     </ body> 
</ html></pre><p>Notice that the body of the HTML page in Code Listing 2 contains the following script: </p><pre class="brush:html;toolbar:false"><%Response.Write(DateTime.Now);%></pre><p>Use Script delimiters  mark the beginning and end of a script. This script is written in C#. It displays the current date and time, rendering the content to the browser script by calling the reply() method. The delimiters  can be used to execute one or more statements. </p><p>Because the reply to () method is often called, Microsoft provides you with a simple way to call the reply to () method. The view in Listing 3 uses  as a simple way to call the reply() method. </p><p>Code Listing 3 - Views \ Home \ Index2.aspx</p><pre class="brush:html;toolbar:false"><%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Index2.aspx.cs”Inherits =“MvcApp.Views.Home.Index2”%> 
<!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“> 
     <头RUNAT = “服务器”> 
          <TITLE>索引2 </ TITLE> 
     </ HEAD> 
     <BODY> 
          <DIV> 
               的当前日期和时间是:
               <%= DateTime.Now%> 
          </ DIV> 
     </ BODY> 
< / HTML></pre><p>You can use any .NET language to generate dynamic content in the view, you can use Visual Basic.Net or C# to write your controllers and views. </p><p>4. Use HTML Helpers to generate view content</p><p>为了使向视图中添加内容更加容易一些,你可以利用叫做HTML Helper的东西.HTML Helper是一个生成<a href="http://www.php.cn/wiki/57.html" target="_blank">字符串</a>的方法。你可以使用HTML帮助者来生成标准的<a href="http://www.php.cn/code/5013.html" target="_blank">HTML元素</a>,例如文本框,链接,下拉框和列表框。</p><p>举个例子,代码清单4中的视图利用了两个HTML Helpers,TextBox()和Password(),用于生成一个登录窗体(见图2)。</p><p>代码清单4 - \ Views \ Home \ Index3.aspx</p><pre class="brush:html;toolbar:false"><%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Index3.aspx.cs”Inherits =“MvcApp.Views.Home.Index3”%> 
<!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>登录表单</ title> 
     </ head> 
     <body> 
          <p> 
               <form method =“post”action =“/ Home / Login”> 
                    <label for =“userName” >用户名:</ label> 
                    <br />
                    <%= Html.TextBox(“userName”)%> 
                    <br /> <br /> 
                    <label for =“password”>密码:</ label> 
                    <br /> 
                    <%= Html.Password(“password” %> 
                    <br /> <br /> 
                    <input type =“submit”value =“登录”/> 
               </ form> 
          </ p> 
     </ body> 
</ html><br /> <%= Html.Password( “密码”)%> <br /> <br /> <INPUT TYPE = “提交”值= “登录”/> </ FORM> </ DIV> </ body> </ html><br /> <%= Html.Password( “密码”)%> <br /> <br /> <INPUT TYPE = “提交”值= “登录”/> </ FORM> </ DIV> </ body> </ html></pre><p><img src="https://img.php.cn//upload/image/696/130/751/1495257725160675.png" title="1495257725160675.png" alt="Detailed introduction to ASP.NET MVC--View"></p><p>所有的HTML帮助者方法都在视图的<a href="http://www.php.cn/code/426.html" target="_blank">Html属性</a>上调。举个例子,你可以通过调用Html.TextBox()方法来呈现(render)一个文本框。</p><p>注意,当你在调用HTML Helper时,必须使用脚本分隔符。HTML Helper只是返回一个字符串你需要调用Response.Write()来将字符串呈现到浏览器中。</p><p>使用HTML帮助方法是可选的。它们通过减少你编写的HTML和脚本数量来使开发更为简单。代码清单5中的视图呈现了与代码清单4中完全相同的窗体,但是没有使用HTML助手。</p><p>代码清单5 - \ Views \ Home \ Index4.aspx</p><pre class="brush:html;toolbar:false"><%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Index4.aspx.cs”Inherits =“MvcApp.Views.Home.Index4”%> 
<!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>没有帮助的登录表单</ title> 
     </ head> 
     <body> 
          <p> 
               <form method =“post”action =“/ Home / Login”> 
                    <label for = userName“>用户名:</ label> 
                    <br />
                    <输入名称= “userName的”/> 
                    <br /> <br /> 
                    </标签>:密码<用于= “密码”的标签> 
                    <br /> 
                    <输入名称= “密码”类型= “密码”/> 
                    < br /> <br /> 
                    <input type =“submit”value =“登录”/> 
               </ form> 
          </ p> 
     </ body> 
</ html></标签> <br /> <输入名称= “密码”类型= “密码”/> <br /> <br /> <INPUT TYPE = “提交”值= “登录”/> </ FORM> < / p> </ body> </ html></标签> <br /> <输入名称= “密码”类型= “密码”/> <br /> <br /> <INPUT TYPE = “提交”值= “登录”/> </ FORM> < / p> </ body> </ html>/ body> </ html>/ body> </ html></pre><p>你可以创建自己的HTML帮助者。据个例子,你可以创建一个GridView()Helper方法,它自动地在一个<a href="http://www.php.cn/code/5022.html" target="_blank">HTML表格</a>中显示一系列的数据库记录。我们将在创建自定义HTML帮助者这篇教程中探讨这一话题。</p><p style="padding: 0px; margin: 2em 0px 1em; font-size: 25px; color: rgb(51, 51, 51); font-family: " microsoft yahei white-space: normal>5.使用ViewData属性将数据传递给视图</p><p>你可以使用视图的另一个属性,ViewData的属性,将数据从控制器传递给视图。例如,代码清单6中的控制器向ViewData的添加了一条消息。</p><p>代码清单6 - ProductController.cs</p><pre class="brush:html;toolbar:false">使用系统; 
使用System.Collections.Generic; 
使用System.Linq; 
使用System.Web; 
使用System.Web.Mvc; 
namespace MvcApp.Controllers 
{ 
     public class ProductController:Controller 
     { 
          public ActionResult Details()
          { 
               ViewData [“message”] =“Hello World!”; 
               return View(); 
          } 
     } 
}</pre><p>控制器的ViewData属性代表着一个名称/值对的集合。在代码清单6中,详细()方法向ViewData集合中添加了一个名为消息的项,其值为“Hello World!”当视图由详情()方法返回时,ViewData的将会自动传递给视图。</p><p>代码清单7中的视图从ViewData的中获取了消息,并且将消息呈现到了浏览器中。</p><p>代码清单7 - \ Views \ Product \ Details.aspx</p><pre class="brush:html;toolbar:false"><%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“Details.aspx.cs”Inherits =“MvcApp.Views.Product.Details”%> 
<!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“> 
     <头RUNAT = “服务器”> 
          <TITLE>产品详细信息</ TITLE> 
     </ HEAD> 
     <BODY> 
          <DIV> 
               <%=了Html.Encode(计算机[ “消息”])%> 
          </ DIV> 
     </ BODY > 
</ html></pre><p>注意到当前呈现消息时,视图利用了Html.Encode()Helper方法.Html.Encode()HTML Helper方法将例如“”这样的特殊字符编码为在网页面中能够安全显示的字符。无论何时呈现用户提交到网站的内容时,你都应该对内容进行编码,以避免的<a href="http://www.php.cn/wiki/48.html" target="_blank">JavaScript</a>注入攻击。</p><p>(因为我们自己在ProductController的中创建了消息,所以并不是真的需要对消息进行编码。然而,当在视图中显示获取自的ViewData中的内容时,总是调用了Html.Encode()是一个很好的习惯。)</p><p>在代码清单7中,我们利用了的ViewData来将一个简单的字符串消息从控制器传递到了视图。你也可以使用的ViewData将其他类型的数据从控制器传递到视图,例如一个数据库记录集合。举个例子,如果你想要在视图中显示产品数据库表的内容,那么你可以将数据库记录的集合保存在ViewData的中进行传递。</p><p>你也可以从控制器向视图传递强类型查看数据。我们将在教程“理解强类型查看数据和视图”中探讨这个话题。</p><p><span style="color: rgb(51, 51, 51); font-family: " microsoft yahei font-size:>总结</span></p><p>这篇教程提供了对ASP.NET MVC视图,视图数据(查看数据)和HTML帮助者的一个简短的介绍。在第一部分,你学习了如何向项目中添加新的视图你学习了必须将视图添加到正确的文件夹中,以使其能够被特定的控制器调用。接下来,我们讨论了HTML帮助者这一主题。你学习了HTML帮助者是如何轻松地生成标准的HTML内容的最后,你学习了如何利用ViewData将数据从控制器传递给视图。</p><p>【相关推荐】<br></p><p>1. <a href="http://www.php.cn/csharp-article-362647.html" target="_self">什么是ASP.NET MVC ?总结ASP.NET MVC</a></p><p>2. <a href="http://www.php.cn/csharp-article-362646.html" target="_self">详细介绍ASP.NET MVC--控制器(controller)</a></p><p>3. <a href="http://www.php.cn/csharp-article-362650.html" target="_self">深入了解ASP.NET MVC与WebForm的区别</a></p><p>4. <a href="http://www.php.cn/csharp-article-362644.html" target="_self">Detailed introduction to ASP.NET MVC--routing</a></p><p>5. <a href="http://www.php.cn/csharp-article-361982.html" target="_self">Code example for developing WeChat custom menu editing tool through asp.net mvc</a></p></body></html>
<p>The above is the detailed content of Detailed introduction to ASP.NET MVC--View. For more information, please follow other related articles on the PHP Chinese website!</p></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="Detailed introduction to ASP.NET MVC-routing" href="/faq/362644.html">Detailed introduction to ASP.NET MVC-routing</a></span><span>Next article:<a class="dBlack" title="Detailed introduction to ASP.NET MVC-routing" href="/faq/362646.html">Detailed introduction to ASP.NET MVC-routing</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="/faq/339563.html" title=".Net Core Graphic Verification Code" class="aBlack">.Net Core Graphic Verification Code</a><div class="clear"></div></li><li><b></b><a href="/faq/339607.html" title=".NET Core configuration file loading and DI injection of configuration data" class="aBlack">.NET Core configuration file loading and DI injection of configuration data</a><div class="clear"></div></li><li><b></b><a href="/faq/339782.html" title=".NET Core CLI tool documentation dotnet-publish" class="aBlack">.NET Core CLI tool documentation dotnet-publish</a><div class="clear"></div></li><li><b></b><a href="/faq/345608.html" title="asp.net uses .net controls to create drop-down navigation menus" class="aBlack">asp.net uses .net controls to create drop-down navigation menus</a><div class="clear"></div></li><li><b></b><a href="/faq/346494.html" title="How to get the name of the controller in Asp.net MVC" class="aBlack">How to get the name of the controller in Asp.net MVC</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="/"><b class="icon1"></b><p>Home</p></a></li><li><a href="/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="/" >Home</a></div><div class="swiper-slide"><a href="/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="/course.html" >Course</a></div><div class="swiper-slide"><a href="/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="/xiazai"  >Download</a></div><div class="swiper-slide"><a href="/game" >Game</a></div><div class="swiper-slide"><a href="/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs"  ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a  onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan "  href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a  onclick="javascript:;" class="language course-right-orders chooselan chooselanguage"  href="javascript:;"><span>English</span><span>(EN)</span></a><a  onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan "  href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a></div></div><script>            var swiper = new Swiper('.nphpNavSwiper1', {
                slidesPerView : 'auto',
                observer: true,//修改swiper自己或子元素时,自动初始化swiper
                observeParents: true,//修改swiper的父元素时,自动初始化swiper

            });
        </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) {
    var _times = times || -1, //100次
    _interval = interval || 20, //20毫秒每次
    _self = this,
    _selector = this.selector, //选择器
    _iIntervalID; //定时器id
    if( this.length ){ //如果已经获取到了,就直接执行函数
        func && func.call(this);
    } else {
        _iIntervalID = setInterval(function() {
            if(!_times) { //是0就退出
                clearInterval(_iIntervalID);
            }
            _times <= 0 || _times--; //如果是正数就 --

            _self = $(_selector); //再次选择
            if( _self.length ) { //判断是否取到
                func && func.call(_self);
                clearInterval(_iIntervalID);
            }
        }, _interval);
    }
    return this;
}
$("table.syntaxhighlighter").wait(function() {
    $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>");
});
$(document).on("click", ".cnblogs_code_footer",function(){
      $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide();
});
$('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}});
</script></body></html>