foreach循环遍历视图模型中的不同模型以显示链接

时间:2013-02-28 09:24:32

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

我有两个名为objects和apartments的表,它们与名为apartmentIDObjectID的外键“连接”。我的控制器和模型非常简单:

型号:

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


    }
}

我的控制器是:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Projekt.Models;

namespace Projekt.Controllers
{
    public class WrapperController : Controller
    {
        public ActionResult Index()
        {
            WrapperModel wrapperModel = new WrapperModel();
            return View(wrapperModel);
        }
    }
}

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

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

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

1 个答案:

答案 0 :(得分:1)

首先初始化你的模型

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

视图

@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){}

尝试上述内容或修改预期结果的代码。然后提出更具体的问题