C# 在一个视图中使用来自 2 个模型的上下文

我需要帮助在一个视图中使用 2 个模型的上下文。我需要使用ZanrID和Ime来自ZanrModel.cs


这是ZanrModel.cs代码:


using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;


namespace WebApplication1.Models

{

    [Table("Zanr")]

    public class ZanrModel


    {

        [Key]

        public int ZanrID { get; set; }


        public string Ime { get; set; }


    }

}

我想使用ZanrdID并且Ime在这个视图中我使用KnjigaModel.cs


@model IEnumerable<WebApplication1.Models.KnjigaModel>


@{

    ViewBag.Title = "Index";

    Layout = "~/Views/Shared/_Layout.cshtml";

}



<h2>Index</h2>


<a href="/Knjiga/Create" class="btn btn-warning">Dodaj novu knjigu</a>

<table class="table">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.InventarniBroj)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Pisac)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Naslov)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.GodinaIzdavanja)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.MestoIzdavanja)

        </th>

        <th>

        </th>

        <th>

        </th>

        <th>

        </th>

    </tr>


    @foreach (var item in Model)

    {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.InventarniBroj)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Pisac)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Naslov)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.GodinaIzdavanja)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.MestoIzdavanja)

        </td>

    }


</table>

是的,我想创建一个用户可以选择 他们想要使用的内容的dropdown menu地方。我有和的数据库,这是它的图片:Knjiga/Create.cshtmlZanrKnjigaZanr


繁花不似锦
浏览 53回答 1
1回答

蝴蝶刀刀

我相信最好的方法是创建一个 ViewModel 对象来包含两个模型对象的组合。将模型直接放在视图上并不是一个好的做法。//New class outside the view.Public class KnjigaZanrVM {IEnumerable<KnjigaModel> Knjiga {get} IEnumerable<ZanrModel> Zanr {get}}//on the View@model WebApplication1.ViewModel.KnjigaZanrVM@{    ViewBag.Title = "Index";    Layout = "~/Views/Shared/_Layout.cshtml";}...@foreach (var item in Model.Knjiga)    {    <tr>        <td>            @Html.DisplayFor(modelItem => item.InventarniBroj)        </td>        <td>...foreach (var item in Model.Zanr)    {    <tr>        <td>            @Html.DisplayFor(modelItem => item.ZanrID)        </td>        <td>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5