Razor foreach循环通过视图模型中的不同模型来显示链接

Razor foreach循环通过视图模型中的不同模型来显示链接,razor,asp.net-mvc-4,entity-framework-5,Razor,Asp.net Mvc 4,Entity Framework 5,我有两个名为objects和partments的表,它们通过名为apartmentID和ObjectID的外键“连接”。我的控制器和型号非常简单: 型号: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Projekt.Models { public class WrapperModel { public IEnumer

我有两个名为objects和partments的表,它们通过名为
apartmentID
ObjectID
的外键“连接”。我的控制器和型号非常简单:

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Projekt.Models
{
    public class WrapperModel
    {

        public IEnumerable<Projekt.Models.objects> Objects { get; set; }
        public IEnumerable<Projekt.Models.apartments> Apartments { get; set; }


    }
}
我想创建一个视图,该视图将使用@foreach循环:

  • 获取每个对象的名称,并将该名称链接到其
    Details.cshtml
    页面

  • 显示链接到对象链接旁边的
    Details.cshtml
    页面的公寓Id


首先初始化您的型号

public ActionResult Index()
{
    // db is your DbContext or your entity that is represented your DB.
    YourDbContext db = new YourDbContext();

    WrapperModel wrapperModel = new WrapperModel();
    wrapperModel.Objects = db.Objects; // from your db
    wrapperModel.Apartments = db.Apartments;// from your db


    return View(wrapperModel);
}
看法

控制器详细信息操作

public ActionResult Details(int id){}

尝试上面的方法,或者修改代码以获得预期的结果。然后问更具体的问题

我不理解“来自你的db”部分。应该去那里干什么?你能给我举个例子吗?嗨,这个模型可以用for循环而不是foreach来显示吗?当我试图将数据从视图提交到操作结果时,得到的是空值
@model WrapperModel 

@foreach(var item in Model.Objects)
{
    // list items in html elements
    @Html.ActionLink(item.name, "Details", "Controller", new { id = item.id })
}

@foreach(var item in Model.Apartments)
{
    // list items in html elements
    // link to details page
}
public ActionResult Details(int id){}