为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁花不似锦 2023-12-11 16:30:06
我需要帮助在一个视图中使用 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
查看完整描述

1 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

我相信最好的方法是创建一个 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>


查看完整回答
反对 回复 2023-12-11
  • 1 回答
  • 0 关注
  • 49 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信