Daniel Crisostomo
Daniel Crisostomo

Reputation: 75

Getting data from database with specific columns MVC4

I'm new in MVC 4. please help in getting data from database in MVC 4. i don't know how to access it from my view.

here's my code:

public ActionResult Index()
{
    var qry = from q in db.SystemUsers
              select new
              {
                  q.Username,
                  q.Password,
                  q.FirstName,
                  q.LastName,
                  q.MiddleName
              };

    return View(qry);
}

Upvotes: 2

Views: 1156

Answers (1)

rhughes
rhughes

Reputation: 9583

What you are looking for is a ViewModel.

This is an object which contains the data required to render your view. They are beneficial because they allow strongly typed values in your view. This helps out with Unit Testing, Intellisense, keeping bugs and runtime errors to a minimum and also forces you to know your view well by ensuring you are passing them only the data they need.

In your case, it may be defined as follows:

public struct SystemUsersIndexViewModel
{
    public string UserName;
    public string Password;
    public string FirstName;
    public string LastName;
    public string MiddleName;
}

To use this, you would do the following:

public ActionResult Index()
{
    var qry = from q in db.SystemUsers
              select new SystemUsersIndexViewModel
              {
                  UserName = q.Username,
                  Password = q.Password,
                  FirstName = q.FirstName,
                  LastName = q.LastName,
                  MiddleName = q.MiddleName
              };

    return View(qry);
}

In your view, you would let MVC know you are using this ViewModel by doing the following:

@model IEnumerable<SystemUsersIndexViewModel>

Upvotes: 2

Related Questions