开发者

MVC3 EditorFor and generic types throws error

I have a Generic type SelectableViewModel

public class SelectableViewModel<T> where T : class
{
    public SelectableViewModel(T model)
    {
        Model = model;
    }

    public T Model { get; set; }
    public bool Selected { get; set; }
}

It wraps a ViewModel so that the user can select or deselect the model from the view.

Controller method

public ActionResult ListReconsiledAssignments()
{
    return View(
        assignmentRepository.ListReconsiled()
            .Select(a => new SelectableViewModel<Assignment>(a))
        );
}

The view

@model IEnumerable<SelectableViewModel<Assignment>>

@{
    ViewBag.Title = "Request snapshot";
}

<h2>Request snapshot</h2>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Number</th>
            <th>Name</th>
        </tr>
    </thead>
    @Html.EditorFor(m => 开发者_JAVA百科m, "SelectableAssignment")
</table>

The editor for template named SelectableAssignment.cshtml

@model SelectableViewModel<Assignment>

<tr>
    <td>@Html.CheckBoxFor(m => m.Selected)</td>
    <td>@Model.Model.KufId</td>
    <td>@Model.Model.Name</td>
</tr>

This throws exception

The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereSelectListIterator2[Domain.Assignment,Web.Models.SelectableViewModel1[Domain.Assignment]]', but this dictionary requires a model item of type 'Web.Models.SelectableViewModel`1[Domain.Assignment]'.


That is because the editor template requires single SelectableViewModel<Assignment>, but you pass IEnumerable<SelectableViewModel<Assignment>> and explicitely instruct it to use "SelectableAssignment" template, so exception is thrown. You could iterate over your model and call editor template one by one like this:

@foreach(var item in Model)
{
   @Html.EditorFor(m => item, "SelectableAssignment")
}

Or, simply, remove that template name from EditorFor method call from your code. Framework should figure out that it should call EditorFor for every item in passed collection

@Html.EditorFor(m => m)

Or, the same, call

@Html.EditorForModel()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜