ASP.NET MVC 学习2、从Controller传递数据到View

时间:2022-03-09 17:46:01
 

参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-view

一,Controller 中的ActionResult方法会用一个View Template生成HTML页面反馈到浏览器中:

1,修改Index方法如下

public ActionResult Index() { return View();}

2,在Index 方法中右键,添加View视图,Views视图下的HelloWorld文件夹中生成了对应的Index.cshtml文件

ASP.NET MVC 学习2、从Controller传递数据到View

3,打开index.cshtml文件,并添加一行html代码如下:

@{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页面

注意到:上面所显示的这个index.cshtml的页面标题却是”index-我的ASP.NET MVC…”,这是因为index.cshtml调用了_layout.cshtml模板

下面我们来改一下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:

ASP.NET MVC 学习2、从Controller传递数据到View

三,传输数据从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显示效果:

ASP.NET MVC 学习2、从Controller传递数据到View