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>

  • 相关阅读:
    Django: 获取头信息
    好用工具:火狐浏览器的境内境外版本区分
    Django: request.GET.get()
    es6: 展开运算符
    Vue: 配置axios基准路径并使用
    js: 获取Blob的值
    ApiPost: Error:ESOCKETTIMEDOUT
    Vue错误:Cannot read properties of undefined (reading '$router')
    git报错:error: Your local changes to the following files would be overwritten by checkout:
    Django: request.query_params取值
  • 原文地址:https://www.cnblogs.com/easypass/p/2248950.html
Copyright © 2011-2022 走看看