2

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

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.