foreach循环浏览视图模型中的不同模型以显示链接 [英] foreach loop through different models in the view model to display links

查看:78
本文介绍了foreach循环浏览视图模型中的不同模型以显示链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个称为对象和公寓的表,它们与名为apartmentIDObjectID的外键连接".我的控制器和模型非常简单:

I have two tables called objects and apartments, which are "connected" with foreign keys called apartmentID and ObjectID. My controller and model are pretty simple:

型号:

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循环的视图:

I want to make a view that will use @foreach loop to:

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

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

display Id of the apartment linking to its Details.cshtml page next to the Object link.

推荐答案

首先初始化模型

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

尝试上述类似方法或修改该代码以达到预期的结果.然后问更具体的问题

try something like above or modify that code for your expected result. And then ask more specific question

这篇关于foreach循环浏览视图模型中的不同模型以显示链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆