Editor Template (Radio Button List) and Model Item Passed into Dictionary is of type [enum] but dictionary requires model type X

StackOverflow https://stackoverflow.com/questions/9439388

Question

Looked around at similar titles, but nothing on point or nothing worked. I understand why I get the error, I am just trying to figure out how I can fix it to use my EditorForModel. I am getting this error:

The model item passed into the dictionary is of type 'MyNameSpace.ViewModels.MyData+MyEnum', but this dictionary requires a model item of type 'MyNameSpace.ViewModels.MyData'.

My model:

    [UIHint("MyRadioButton")]
    public MyEnum MyRadioRadioButton { get; set; }

    //
    //
    public enum MyEnum
    {
        Choice1,
        Choice2            
    }

I am using [UIHint] to call up an EditorTemplate called MyRadioButton.cshtml. Now, my view is also calling an EditorTemplate using @Html.EditorForModel. This is the part of the view page which is calling the general template:

@Html.EditorForModel("BasicDetails")

Both templates are in the '/Shared/EditorTemplates/' folder.

This is the MyRadioButton.cshtml template:

<td>
    <div class="radio">
        @Html.RadioButtonFor(m => m.MyRadioButton, "Choice1")<br />
        @Html.RadioButtonFor(m => m.MyRadioButton, "Choice2")
    </div>
</td>

This is the BasicDetails.cshtml (called by @Html.EditorForModel above):

@using MyNameSpace.ViewModels
@model MyData
<table>
    @Html.EditorFor(x => x.FirstName)
    @Html.EditorFor(x => x.LastName)
    @Html.EditorFor(x => x.MyRadioButton) //This is where my error is thrown
</table>

I want to avoid anything complex in the radiobuttonlist Editor Template above because there is other stuff going on in there (I stripped out everything superfluous and am still getting the error). I use the particular radiobuttonlist multiple times in different views (which is why I wanted to template it rather than copy/paste). Any advice?

Was it helpful?

Solution 2

For now I am simply relying on EditorForModel to pull a template from /EditorTemplates/, and instead of using [UIHint] for the radio button list, I am just inserting the @Html.RadioButtonFor group inside that template. This works for me and serves to minimize copy/pasting.

At some point I have to learn to stop with the template > for a template > for a template paradigm and know when enough is enough. :)

OTHER TIPS

From BasicDetails.cshtml you are invoking EditorFor as @Html.EditorFor(x => x.MyRadioButton).

That means the model type passed to EditorFor is Enum type.

But inside the EditorFor Template (MyRadioButton.cshtml) ,i think you have used the class as model. so the errors.

So, we need to change the model type in MyRadioButton.cshtml to MyEnum (With namespace)

or

pass the same model to editorFor template @Html.EditorFor(x=>x,"MyRadioButton")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top