通过在视图模型以显示链接不同的模型foreach循环(foreach loop through di

2019-10-17 18:24发布

我有两个表称为对象和公寓,这是与外键被称为“连接” 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对象旁边的链接页面。

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

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



文章来源: foreach loop through different models in the view model to display links