Search code examples
asp.netlistasp.net-mvc-3

Displaying list of items. In my case list of users


I have been trying to list all the users in my database but I am having a hard time. I am new to MVC3 pls help. :)

This is my UserList

using System;
using System.Data.Entity;
using System.Collections.Generic;
 using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using MVCDemo.Models.DB;
using MVCDemo.Models.ViewModel;

namespace MVCDemo.Models.ViewModel
{


    public class UserList
    {

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ContactNumber { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }

     }

    public class Users
    {
        private DeveloperReportEntities dre = new DeveloperReportEntities();
        public UserList _userList = new UserList();


        public Users()
        {
            DB.Users_Tbl userTBL = new DB.Users_Tbl();
            _userList.FirstName = userTBL.FirstName;
            _userList.LastName = userTBL.LastName;
            _userList.Email = userTBL.Email;
            _userList.Address = userTBL.Address;
            _userList.ContactNumber = userTBL.ContactNo;
            _userList.Username = userTBL.Username;
            _userList.Password = userTBL.Password;
         }


    }
}

which is supposed to be controlled through here: AdminController

    public class AdminController : Controller
    {
        //
         // GET: /Admin/

        public ActionResult AdminHomePage()
        {
             return View();
        }

        public ActionResult ViewAll()
         {
            return View();
         }
     }   

in my solution explorer i have a samplemodel.edmx in model folder


Solution

  • First, the Users class should encapsulate a List of User. Here's what it should look like:

    /Controllers/Admin/AdminController.cs

    public class User
    {
       public string FirstName { get; set; }
       public string LastName { get; set }
    }
    
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        public ActionResult AdminHomePage()
        {
             return View();
        }
    
        public ActionResult ViewAll()
        {
            var userTBL = new DB.Users_Tbl();
            var users = userTBL.Select(u => new User { FirstName = u.FirstName, LastName = u.LastName };
            return View(users);
        }
     }
    

    /Views/Admin/ViewAll.cshtml

    @model List<User>
    <ul>
    @foreach(var user in Model)
    {
       <li>@user.FirstName @user.LastName</li>
    }
    </ul>