簡體   English   中英

在MVC應用程序中使用兩個模型,一個在視圖中,一個在局部視圖中

[英]Using two models in MVC application, one in a view and one in a partial

我遇到了麻煩。 我有以下觀點

@model IEnumerable<Tipstr.Models.Posts>

<div class ="mainC">
<div class = "leftContent">


  @Html.Partial("_LeaderboardPartial")

</div>
<div class = "rightContent">
@foreach (var item in Model) {

        <h1 class ="ptitle">
        @Html.DisplayFor(modelItem => item.title)
            </h1>
   <p class ="date">
       posted @Html.DisplayFor(modelItem => item.date)
    </p>
<p class ="post">
        @Html.DisplayFor(modelItem => item.body)
  </p>
<hr />
}
</div>
</div>
    <div class="Cpad">
        <br class="clear" /><div class="Cbottom"></div><div class="Cbottomright">                           
    </div>
    </div>

我有一個_LeaderboardPartial,如圖所示

 @model IEnumerable<Tipstr.Models.Leaderboard>


<table id="pattern-style-a" summary="Meeting Results">
<thead>
    <tr>
        <th scope="col">Username</th>
        <th scope="col">Tipster Score</th>

    </tr>
</thead>
<tbody>
@foreach (var item in Model) {



    <tr>
        <td>@Html.DisplayFor(modelItem => item.userName)</td>
        <td> @Html.DisplayFor(modelItem => item.score)</td>

    </tr>

}
    </tbody>
 </table>

我似乎無法使其正常工作,我認為這與從布局傳入一個模型,然后從局部傳入另一個模型有關。 我該如何解決? 我收到以下錯誤:

傳遞到詞典中的模型項的類型為'System.Collections.Generic.List 1[Tipstr.Models.Posts]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable類型為'System.Collections.Generic.IEnumerable 1[Tipstr.Models.Posts]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 。[Leaderboard]]。

正如@David Tansey所說,您可以擁有一個包含對這兩種類型的引用的視圖模型

public class MyViewModel
{
    public MyViewModel(IEnumerable<Posts> posts, 
                       IEnumerable<Leaderboard> leaderboard)
    {
        //you can add null checks to ensure view model invariants

        this.Posts = posts;
        this.Leaderboard = leaderboard;
    }

    public IEnumerable<Posts> Posts { get; private set; }
    public IEnumerable<Leaderboard> Leaderboard{ get; private set; }
}

在主視圖中,您將這樣調用Html.Partial

@model MyViewModel

<div class ="mainC">
<div class = "leftContent">


@Html.Partial("_LeaderboardPartial", this.Model.Leaderboard)

</div>
....

如果執行此操作,則應更改foreach以通過Model.Posts而不是Model進行迭代

@foreach (var item in this.Model.Posts)

這行代碼:

在第一個視圖中, @Html.Partial("_LeaderboardPartial")表示將其自身的模型IEnumerable<Tipstr.Models.Posts>發送到局部。

該部分期望引用為IEnumerable<Tipstr.Models.Leaderboard>類型。

也許您需要一個包含對這些類型之一的引用的視圖模型?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM