Question

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 ?

Was it helpful?

Solution

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>
...

OTHER TIPS

to achieve this you should try like this

public class MainPageModel
  {
    public PosteModel Model1{get; set;}
    public AppMetierModel Model2{get; set;}
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top