简体   繁体   中英

Viewmodel Data Binding

Playing around with viewmodels to try and get my head around it, as we came to learn about half way through a project that using Entity Framework models to display the data isn't the way we should be doing it, so we're trying to learn the right way, or I think we are anyway.

I have a table called Users in a database, and have created an ADO.net Entity Data Model which I simply called "MainModel" for now, and then created a new Class file called "MainViewModel".

In this view model, I've taken properties from the User table in MainModel which we would want to display in a view on a table to show every database entry. The MainViewModel code is as follows:

    namespace WebApplication9.Models
{
    public class MainViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Company { get; set; }
    }
}

I then have a controller called MainController, which has an ActionResult for Index which is as follows:

public ActionResult Index(MainViewModel viewModel)
        {                       
            var users = new User()
            {
                FirstName = viewModel.FirstName,
                LastName = viewModel.LastName,
                EMail = viewModel.Email,
                Company = viewModel.Company,
            };

            List<MainViewModel> viewModelList = new List<MainViewModel>();

            return View(viewModelList);
        }

Up to this point, I have no idea where to go next and unfortunately everything I've read is just confusing me more. It does display a table, with the FirstName, LastName, Email and Company table headers, but it doesn't display any data in the view.

Any help would be hugely appreciated as we're desperate to get going again :)

Thanks

Assuming that's your HttpGet action (although not sure why it takes your viewModel as a parameter?), you're not actually populating your list with anything, you're gonna have to get it from the database and then transform it into your view model ready for displaying, something like:

 public ActionResult Index(MainViewModel viewModel)
    {                       
        var users = context.Users.ToList(); //use your dbContext

        List<MainViewModel> viewModelList = users
            .Select(u => new MainViewModel
            {
                FirstName = u.FirstName,
                LastName = u.LastName,
                Email = u.Email,
                Company = u.Company
            }).ToList();

        return View(viewModelList);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM