在Asp.net MVC4的1个视图中有2个模型(表格)

时间:2013-06-17 12:22:56

标签: entity-framework asp.net-mvc-4

我在数据库中有Konu和Etiketler表。

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        SonerSevincComEntities context = new SonerSevincComEntities();

        var Konular = context.Konu.ToList();
        return View(Konular);
    }

}

在Konu Controller的视图中,

我想调用Etiketler表及其ID。

我已经使用过Konu模型但我想在1 View中使用Etiketler模型。

如何在1个视图页面中调用2个表(模型)?

1 个答案:

答案 0 :(得分:0)

您需要创建一个ViewModel:

public class KonuEtiketlerViewModel
{
   public virtual List<Konu> Konus {get; set;}
   public virtual List<Etiketler> Etiketlers {get; set;}
}

并在您的控制器中:

public ActionResult Index()
{
   SonerSevincComEntities context = new SonerSevincComEntities();
   var viewModel =  new KonuEtiketlerViewModel
   {
       Konus = context.Konu.ToList(),
       Etiketlers = context.Etiketler.ToList()
   }
   return View(viewModel);
}

查看:

@model projectname.ViewModels.KonuEtiketlerViewModel // you must create a new class, preferably inside a ViewModels folder, called KonuEtiketlerViewModel
//you can access all your properties here....