参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-viewhtml
一,Controller 中的ActionResult方法会用一个View Template生成HTML页面反馈到浏览器中:数据库
1,修改Index方法以下浏览器
public ActionResult Index() { return View();}
2,在Index 方法中右键,添加View视图,Views视图下的HelloWorld文件夹中生成了对应的Index.cshtml文件mvc
3,打开index.cshtml文件,并添加一行html代码以下:asp.net
@{ViewBag.Title = "Index";}
<h2>Index</h2>
<p>Hello from our View Template!</p>
4,右击index.cshtml,页面探测器Page Inspector打开(ctrl+K,ctrl+G),可看到生成的html页面,Ctrl+F5刷新(http://localhost:9898/HelloWorld/Index ),咱们看到虽然Controller中的Index方法就只是简简单单的 Return View(),并无特别指定要输出哪一个View Page,可是MVC默认会调用Index.cshtml.这就是MVC中的Hard-Code.布局
以上页面的运行,后须要理解页面具体是怎么运行出来的:从一个ActionResult方法指向View页面显示在浏览器中性能
URL→Controller 中的ActionResult方法→ActionResult方法名对应的Views中同名的视图测试
二,了解_Layout.cshtml页面url
注意到:上面所显示的这个index.cshtml的页面标题倒是”index-个人ASP.NET MVC…”,这是由于index.cshtml调用了_layout.cshtml模板spa
下面咱们来改一下View的模板页面:/Views/Shared/_Layout.cshtml
Layout.cshtml 布局页面,就至关于一个容器,能够把layout页面的布局以及内容套用于其它页面。
Layout.cshtml中的@RenderBody()是占位符,这里代替其它调用Layout.cshtml的页面内容,例如:咱们打开连接http://localhost:9898/Home/About 这时候,about.cshtml的内容就嵌套到了layout.cshtml中的@renderBody()的位置
改变Layout中的Title: ViewBag的值加”-Movie App”
<title>@ViewBag.Title - Movie App</title>
子页面:
@{ ViewBag.Title = "Movie List";} <h2>My Movie List</h2>
ViewBag.Title能够在layout.cshtml和index.cshtml之间进行传值,页面运行之后能够看到title:
三,传输数据从Controller到View:
Controller Classes 在浏览器请求URL的时候被调用
Controller Class中的代码就是处理浏览器请求,从数据库中检索数据,最终调用相应的View显示在浏览器中
View中不该该直接有与数据交互和业务逻辑的部分,View只能够接收从Controller传递过来的数据
这种分离模式,能够让你的代码简洁,测试性能以及可维护性能更高
ViewBag 是一个Dynamic Object,这意味着你能够传递任何类型的数据给它。
ViewBag 没有定义任何属性,直到你赋值给它。
ASP.NET MVC model binding system 会自动映射URL中的参数到Controller的方法的参数中。更新Controller中的Welcome方法以下:
public ActionResult Welcome(string name, int numTimes) { ViewBag.Message = "Hello " + name; ViewBag.NumTimes = numTimes; return View(); }
运行一下,看到数据传递过程:
http://localhost:9898/HelloWorld/Welcome?name=Spring&numtimes=10(URL)
↓url请求传递到HelloWorldController的Welcome方法中
public ActionResult Welcome(string name, int numTimes) { ViewBag.Message = "Hello " + name; ViewBag.NumTimes = numTimes; return View(); }
↓Welcome中的方法的数据传递到View页面中
<ul> @for (int i = 1; i < ViewBag.NumTimes; i++) { <li>@ViewBag.Message</li> } </ul>
.cshtml显示效果: