本文介绍了MVC 3使用两次@model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用两次@Model从我的网站的另一部分是有可能得到的数据?因为现在我有错误,但如果我只有这第一@model一切工作的正确。

外观 - > MVC 3 - 异常详细信息:System.InvalidOperationException

@model IEnumerable<SportsStore.Entities.Towar>
@model IEnumerable<SportsStore.Entities.Kategorie>


@{
    ViewBag.Title = "List";
}

<h2>List</h2>

@foreach (var p in Model)
{
    <div class="item">
         <h3>@p.Nazwa</h3>
         @p.Opis
         <h4>@p.Cena.ToString("c")</h4>
    </div>
}
解决方案

You only can have one Model per View. But you can use another object to declarate the model:

public class SomeViewModel
{
   public IEnumerable<Towar> Towars;
   public IEnumerable<Category> Categories;

   public SomeViewModel(IEnumerable<Towar> towars, IEnumerable<Category> categories) {
     Towars = towars;
     Categories = categories;
   }
}

And then use it in your view like this:

@model SportsStore.Entities.SomeViewModel

@foreach (var item in Model.Towars)
{
  <div class="item">
    <h3>@p.Nazwa</h3>
    @p.Opis
    <h4>@p.Cena.ToString("c")</h4>
  </div>
}
@foreach (var item in Model.Categories) {
  @item.Name @* or what you need down here *@
}

I would also recommend you to use english names in MVC. It's more clear to read and understand ;).

这篇关于MVC 3使用两次@model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 11:41