2013-02-28 42 views
1

我有两个表称为对象和公寓,它们与外部关键字apartmentIDObjectID“连接”。我的控制器和模型非常简单:foreach循环通过视图模型中的不同模型来显示链接

型号:

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页面的公寓的标识。

回答

1

第一initialze你的模型

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

尝试像上面或修改代码,您预期的结果。然后问更具体的问题

+0

我不明白的部分“从你的分贝”。应该去那里?你能举个例子吗? – 2013-03-05 09:20:52

+0

我更新了我的答案... – 2013-03-05 09:26:58

相关问题