使用弱类型的viewData[] 来显示数据

    技术2026-06-10  2

    controller中的代码:

    public ActionResult Index() { List<OP_CashCoupon> op = new List<OP_CashCoupon>(); for (int i = 0; i < 10; i++) { op.Add(new OP_CashCoupon {cashCouponID="3"}); } ViewData["OP_CashCoupon"] =op; return View(); } 

     

    其中OP_CashCoupon表示model中的一个class,

     

    在view页中引用代码:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index</h2> <%=Html.ActionLink("链接", "Index", null, new {@class="link1" }) %> <%=Html.TextBox("Name1", "my name is wtq", new { id = "MyName", style = "color:red",@class="link1"})%> <ul> <% foreach( var s in (ViewData["OP_CashCoupon"] as IEnumerable<test.Models.OP_CashCoupon>)){ %> <li><%=s.cashCouponID %></li> <%} %> </ul> </asp:Content>

     

    (ViewData["OP_CashCoupon"] as IEnumerable<test.Models.OP_CashCoupon>) 此就将viewData转化为OP_CashCoupon此类 型,同时记住引用命名空间。

    最新回复(0)