MVC - 使用 C# 将 ViewModel 传递给 View

发布于 2024-12-12 17:49:58 字数 380 浏览 4 评论 0原文

我有一个这样的 ViewModel:

public class EmployeeViewModel
{


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



}

我喜欢将此视图模型传递给执行需要两个表的创建的视图。

我尝试在控制器中执行以下操作,将信息传递到视图,但没有成功:

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

原因是员工和预算的值都为空。 如何将此信息传递给视图,以便它了解这两个表?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

廻憶裏菂餘溫 2024-12-19 17:49:58

如果这样做,您将在 ViewModel 属性中获得引用:

public class EmployeeViewModel
{
    Employees employee { get; set; }
    Budget budget { get; set; }

    public EmployeeViewModel()
    {
         employee = ... initialize Employee list/set...
         budget = ... initialize budget
    }

}

如果员工和预算是 LINQ/ADO EF 模型,您可以将数据库中的数据附加到控制器中:

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

}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文