Using multiple models in a single controller [closed]

有些话、适合烂在心里 提交于 2019-11-27 16:29:21

You have different options you can use anyone of them

Use ViewModel

For view model you have to create a class and in this class you will define all models as properties of this class.Here are two classes.

public class EmployeeDetails
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }

}

public class Employee
{
    public int Id { get; set; }
}

Here is viewmodel

public class ViewModel
{
    public Employee emp { get; set; }
    public EmployeeDetails empdet{ get; set; }
}

Now in Controller you will do like this

public ActionResult About()
{
        ViewModel vm = new ViewModel();
        vm.emp = new Employee();
        vm.empdet = new EmployeeDetails();
        return View(vm);
}

And in view you will receive it like this

@model ViewModel

And as you have stated that you are getting error table has no key defined you should properly define keys for the tables.

Use Tuple

Tuple is used to store different types.You can store your required classes object in it and pass to view

In controller

Tuple<int, string> tuple = new Tuple<int, string>(1, "Hello world");
return View(tuple);

In view you will receive it like this

@model Tuple<int,string>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!