MVC3.0入门学习笔记页面传值ViewData

MVC 模式一个典型的特征是严格的功能隔离。Model模型、Controller 控制器和 View视图各自定义了用和职责,且相互之间定义好的方式进行沟通。这有助于提升测试性和代码重用。 当 Controller 决定呈现HTML 响应给客户端是,它负责显式传递给View 模板所有需要的数据。View 模从不执行任何数据查询或应用程序逻辑  –  仅仅负责呈现 Model或 Controller 传递过来的数据。

1.ViewData[]字典:


   简单的传值

   首先我们在控制器HomeController.cs中创建一个ViewData[]字典:

   public ActionResult Index()
        {
            ViewData["str"] = "这是一个传递的值";

            return View();
        }

   b.然后我们就可以在相对应得Index.cshtml中写上:

    @ViewData["str"]

   c.编译运行,我们就可以看到在View页面中已经可以看到我们在Controller传过来的值了

2 传递复杂点的参数

在 Controllers\HomeController.cs修改成以下方法

public ActionResult Index()
        {

            List<string> colors = new List<string>();
            colors.Add("red");
            colors.Add("green");
            colors.Add("blue");
            ViewBag.List = colors;
            ViewBag.Name = "jcgh";
            ViewBag.Age = "25";
            ViewData["str"] = colors;

            return View();
        }

Views\Home\Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>jcghs</h2>

@foreach (var a in ViewData["str"] as List<string>)
{
    <font color="@a">a</font>
}

F5运行

原文地址:https://www.cnblogs.com/jcgh/p/2080412.html