Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one 'model' statement is allowed in a file

I try to list data provided models data sent from a SearchController. But, I got this error, that I can't find how to fix it.

Only one 'model' statement is allowed in a file.

Here is the code causes the error :

@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)
    {
        //...
    }
}

How do I to fix it, please ?

like image 349
user3212730 Avatar asked Jan 29 '14 04:01

user3212730


2 Answers

to achieve this you should try like this

public class MainPageModel
  {
    public PosteModel Model1{get; set;}
    public AppMetierModel Model2{get; set;}
  }
like image 77
Nilesh Gajare Avatar answered Oct 31 '22 15:10

Nilesh Gajare


Only one 'model' statement is allowed in a file.

You can either

  • merge 2 models in one (see Nilesh answer)
  • split views into separate views on controller level and have one model for each view

Sample:

 if (...) 
     return View("View1", model1);
 else 
     return View("View2", model2);
  • use partial views and specify some common model in parent view (like @model IEnumerable) and call sub-view which will use particular type as model:

Sample:

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

And in each partial view you can specify model type:

// ViewForApplications 
@model IEnumerable<Monitoring.Models.AppMetierModel>
...
like image 30
Alexei Levenkov Avatar answered Oct 31 '22 15:10

Alexei Levenkov