foreach loop through different models in the view model to display links

删除回忆录丶 提交于 2019-12-11 10:10:35

问题


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:

Model:

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


    }
}

And my controller is:

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

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

  • take a name of each Object, and link the name to its Details.cshtml page

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


回答1:


first initialze your models

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

view

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

controller detail action

public ActionResult Details(int id){}

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



来源:https://stackoverflow.com/questions/15131826/foreach-loop-through-different-models-in-the-view-model-to-display-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!