亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 157 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號