zoukankan      html  css  js  c++  java
  • ViewBag、ViewData使用

    1、Example - Using ViewData

    Controller 

    public ActionResult Index()
    {
        List<string> colors = new List<string>();
        colors.Add("red");
        colors.Add("green");
        colors.Add("blue");            

        ViewData["listColors"] = colors;
        ViewData["dateNow"] = DateTime.Now;
        ViewData["name"] = "Hajan";
        ViewData["age"] = 25;

        return View();
    }


    View (ASPX View Engine)

    <p>
        My name is 
        <b><%: ViewData["name"%></b>
        <b><%: ViewData["age"%></b> years old.
        <br />    
        I like the following colors:
    </p>
    <ul id="colors">
    <% foreach (var color in ViewData["listColors"as List<string>){ %>
        <li>
            <
    font color="<%: color %>"><%: color %></font>
        </
    li>
    <% } %>
    </ul>
    <p>
        <%: ViewData["dateNow"%>
    </p>

    (I know the code might look cleaner with Razor View engine, but it doesn’t matter right? ;) ) 

    2、Example - Using ViewBag

    Controller 

    public ActionResult Index()
    {
        List<string> colors = new List<string>();
        colors.Add("red");
        colors.Add("green");
        colors.Add("blue");

        ViewBag.ListColors = colors; //colors is List
        ViewBag.DateNow = DateTime.Now;
        ViewBag.Name = "Hajan";
        ViewBag.Age = 25;
        return View(); 
    }

    You see the difference?

    View (ASPX View Engine)

    <p>
        My name is 
        <b><%: ViewBag.Name %></b>
        <b><%: ViewBag.Age %></b> years old.
        <br />    
        I like the following colors:
    </p>
    <ul id="colors">

    <% foreach (var color in ViewBag.ListColors) { %>
        <li>
            <font color="<%: color %>"><%: color %></font>
        </li>
    <% } %>

    </ul>
    <p>
        <%: ViewBag.DateNow %>
    </p>

  • 相关阅读:
    jq绑定on事件无效
    数字以0补全
    redis常用操作
    mysql数据操作日常
    centos端口映射
    centos7防火墙操作
    mysql5.7order by问题
    centos无法上网解决方法
    面试题
    ztree 获取子节点所有父节点的name的拼接
  • 原文地址:https://www.cnblogs.com/easypass/p/2248950.html
Copyright © 2011-2022 走看看