Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 IEnumerable of model not finding correct editor template

I have the following model:

public class Filter
{
    public string Field { get; set; }

    public string Operator { get; set; }

    public string Value { get; set; }
}

And the following controller:

public class FilterController
{
    public ActionResult Index()
    {
        IList<Filter> model = new List<Filter>() {
            new Filter(), 
            new Filter()
        };

        return View(model);
    }
}

And the following view:

@model IEnumerable<Filter>
@Html.EditorForModel()

This should look for my EditorTemplate Filter.cshtml, and render the template for each element in the list, right?

Using Glimpse, I notice that MVC is looking for IEnumerable`1.cshtml instead of Filter.cshtml

The same thing happens when I use

@Html.EditorFor(model => model)

When I do this:

@Html.EditorFor(model => model, "Filter")

I get an error saying that Filter.cshtml is expecting a model of type Filter but it received a model of type IEnumerable<Filter>

Am I doing this correctly? Do I need to do anything else to get the list of models to render correctly, using the correct editor template?

like image 913
Kyle Trauberman Avatar asked Oct 09 '22 01:10

Kyle Trauberman


1 Answers

I've definitely had issues in the past with EditorTemplates, but I think it was mostly user error.

One possible workaround is to encapsulate your collection in a single, view model class and pass that to the view

public class MySweetFilterViewModel
{
    public IEnumerable<Filter> Filters { get; set; }
}

Then you could use a single view to pick apart the collection

@model Project.Models.MySweetFilterViewModel
@Html.EditorFor(x => x.Filters)

Just make sure your controller encapsulates

public ActionResult Index()
{
    //...
    return View(new MySweetFilterViewModel() { Filters = model });
}
like image 50
David Fox Avatar answered Oct 12 '22 09:10

David Fox