Search code examples
model-view-controllerviewmodel

MVC - Pass ViewModel to View using c#


I have a ViewModel as such:

public class EmployeeViewModel
{


    Employees employee{ get; set; }
    Budget budget { get; set; }



}

I like to pass this view model to a view that does a create that requires both of the tables.

I tried doing the following in the controller that would pass information to the view but was not successful:

    EmployeeViewModel pvm = new EmployeeViewModel()
    return View(pvm);

The reason being is that the Value of both employee and budget it null. How do I pass this information to the view so it knows about both of the tables?


Solution

  • If you do this, you will have references in the ViewModel properties:

    public class EmployeeViewModel
    {
        Employees employee { get; set; }
        Budget budget { get; set; }
    
        public EmployeeViewModel()
        {
             employee = ... initialize Employee list/set...
             budget = ... initialize budget
        }
    
    }
    

    If Employees and Budgets are LINQ/ADO EF models, you could attach data from database in a controller:

    public class BudgetController : Controller {
    
      public ViewResult Index() {
        var db = new YourContextClass();
        EmployeeViewModel pvm = new EmployeeViewModel();
        pvm.employees = db.Employees.All(); // or some where condition
        pvm.budget = db.Budget.FirstOrDefault(b=> b.Year == DateTime.Now.Year); // if you have Year property in budget model
        return View(pvm);
      }
    
    }