zoukankan      html  css  js  c++  java
  • MVC-控制器向View传值的三种方法

    1.提供视图模型对象

    你能把一个对象作为View方法的参数传递给视图.

    public ViewResult Index()
    {
    DateTime date = DateTime.Now;
    return View(date);
    }

    然后我们在视图中使用Razor的Model关键字来访问这个对象

    @{
    ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    The day is: @(((DateTime)Model).DayOfWeek)

    或者是

    @model DateTime
    @{
    ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    The day is: @Model.DayOfWeek

    2.使用ViewBag(视图包)传递数据

    View  Bag 允许在一个动态的对象上定义任意属性,并在视图中访问它.这个动态的对象可以通过Controller.ViewBag属性访问它.

    public ViewResult Index()
    {
        ViewBag.Message = "Hello";
        ViewBag.Date = DateTime.Now;
        return View();
    }
    
     @{
     ViewBag.Title = "Index";
     }
     <h>Index</h>
     The day is: @ViewBag.Date.DayOfWeek
     <p />
     The message is: @ViewBag.Message

    3. 使用View Data传递数据

    MVC3.0之前,主要是通过这种方式传递数据,它是通过用 ViewDataDictionary类实现的,而不是动态的对象.ViewDataDictionary类是类似标准"键/值"集合,并通过

    Controller类的ViewData属性进行访问的.这个方法,在视图中需要对对象进行转换.

    控制器中:
     public ViewResult Index()
     {
        ViewData["Message"] = "Hello";
        ViewData["Date"] = DateTime.Now;
        return View();
     }
    
    视图中:
     @{
     ViewBag.Title = "Index";
     }
     <h2>Index</h2>
     The day is: @(((DateTime)ViewData["Date"]).DayOfWeek)
     <p />
     The message is: @ViewData["Message"]
  • 相关阅读:
    Python中re(正则表达式)模块学习
    Django(第一次使用心得,及总结)
    Lunix 安装VMware tools
    主键自动生成办法
    常用的android弹出对话框
    JDBC_mysql---防sql注入,存储图片
    java实现md5加密
    sql语句批量处理Batch
    连接mysql数据库2+操作入门
    Oracle事物基础
  • 原文地址:https://www.cnblogs.com/dekevin/p/4155726.html
Copyright © 2011-2022 走看看