Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 270
Nate Pet Avatar asked Mar 22 '26 11:03

Nate Pet


1 Answers

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

}
like image 136
Milan Jaric Avatar answered Mar 24 '26 14:03

Milan Jaric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!