Search code examples
asp.net-mvcasp.net-mvc-2viewdata

getting List data from ViewData in mvc2


i am trying to get List of data from View Data Here is the method which is getting list of all clients from database

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;
                }
            }
        }

and here is the controller

public ActionResult Customers()
        {
            GetSetData data = new GetSetData();

            ViewData["AllClients"] = data.GetAllClients();

          return View();
        }

and here is the 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>

this returns me

System.Collections.Generic.List`1[MvcApplication5.Models.ClientsModels]

the question is how can i get all the data one by one which is in list


Solution

  • First cast ViewData["AllClients"] as List<ClientsModels> as then use a loop.

    Use

    <% foreach (var clientsModel in ViewData["AllClients"] as List<MvcApplication5.Models.ClientsModels>){ %>
        <label><%= clientsModel.Name %></label>                     
    <% } %>