【问题标题】:foreach loop through different models in the view model to display linksforeach 循环遍历视图模型中的不同模型以显示链接
【发布时间】:2013-03-05 17:26:45
【问题描述】:

我有两个名为 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。

【问题讨论】:

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


    【解决方案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){}
    

    尝试上述方法或修改该代码以获得您的预期结果。然后问更具体的问题

    【讨论】:

    • 我不明白“来自您的数据库”的部分。应该去那里做什么?可以举个例子吗?
    • 嗨 是否可以在 for 循环而不是 foreach 中显示此模型?当我尝试从视图提交数据到操作结果时,我得到空值
    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    相关资源
    最近更新 更多