我正在尝试从View Data获取数据列表 以下是从数据库获取所有客户端列表的方法
public List<ClientsModels> GetAllClients()
{
String conStr = conn.GetAccessConnString();
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.Default);
List<ClientsModels> allClientsList = new List<ClientsModels>();
while (reader.Read())
{
allClientsList.Add(new ClientsModels()
{
UserID = Convert.ToString(reader["userID"]),
Name = Convert.ToString(reader["Name"]),
Email = Convert.ToString(reader["Email"]),
Phone = Convert.ToString(reader["Phone"])
});
}
cmd.Dispose();
con.Close();
con.Dispose();
return allClientsList;
}
}
}
这是控制器
public ActionResult Customers()
{
GetSetData data = new GetSetData();
ViewData["AllClients"] = data.GetAllClients();
return View();
}
这是视图
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/NewMaster.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Customers
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Customers</h2>
<%: ViewData["AllClients"].ToString() %>
</asp:Content>
这会让我回头
System.Collections.Generic.List`1[MvcApplication5.Models.ClientsModels]
问题是如何逐一获取列表中的所有数据
答案 0 :(得分:1)
首先将ViewData["AllClients"]
转换为List<ClientsModels>
,然后使用循环。
使用
<% foreach (var clientsModel in ViewData["AllClients"] as List<MvcApplication5.Models.ClientsModels>){ %>
<label><%= clientsModel.Name %></label>
<% } %>