【问题标题】:Only one 'model' statement is allowed in a file文件中只允许有一个“模型”语句
【发布时间】:2014-02-20 17:10:15
【问题描述】:

我尝试列出从 SearchController 发送的模型数据提供的数据。但是,我收到了这个错误,我找不到解决方法。

一个文件中只允许有一个“模型”语句。

这是导致错误的代码:

@if (ViewBag.Type == "nomPoste")
{
    @model IEnumerable<Monitoring.Models.PosteModel>

    if (Model != null)
    {
        foreach (var item in Model)
        {
            //...
        }
    }
    if (Model == null)
    {
        //...
    }
}

@if (ViewBag.Type == "nomApplication")
{
    @model IEnumerable<Monitoring.Models.AppMetierModel>

    if (Model != null)
    {
        foreach (var item in Model)
        {
            //...
        }
    }
    if (Model == null)
    {
        //...
    }
}

请问我该如何解决?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 views


    【解决方案1】:

    要做到这一点,你应该像这样尝试

    public class MainPageModel
      {
        public PosteModel Model1{get; set;}
        public AppMetierModel Model2{get; set;}
      }
    

    【讨论】:

      【解决方案2】:

      一个文件中只允许有一个“模型”语句。

      你可以

      • 将 2 个模型合二为一(请参阅 Nilesh 答案)
      • 在控制器级别将视图拆分为单独的视图,并且每个视图都有一个模型

      示例:

       if (...) 
           return View("View1", model1);
       else 
           return View("View2", model2);
      
      • 使用局部视图并在父视图中指定一些通用模型(如@model IEnumerable)并调用将使用特定类型作为模型的子视图:

      示例:

      @if (ViewBag.Type == "nomApplication"))
      {
            @Html.Partial("ViewForApplications", Model)
      }
      else
      {
            @Html.Partial("ViewForWahtever", Model)
      }
      

      并且在每个局部视图中您都可以指定模型类型:

      // ViewForApplications 
      @model IEnumerable<Monitoring.Models.AppMetierModel>
      ...
      

      【讨论】:

        猜你喜欢
        • 2017-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-07
        • 2012-04-19
        相关资源
        最近更新 更多