开发者

MVC3 Model Binding in the way of my Child Action Method

开发者 https://www.devze.com 2023-04-06 10:16 出处:网络
I am using MVC3 and am trying to leverage the Child Action feature @Html.Action() so I have a View with the following

I am using MVC3 and am trying to leverage the Child Action feature @Html.Action() so I have a View with the following


    @foreach (var item in Model.Items){
        @Html.Action("GetFormItemView", "Question", item});
    }

This calls the following method


    [ChildActionOnly]
    public ActionResult GetFormItemView(FormItem formItem)
    {
        if 开发者_运维技巧(formItem is FormSection)
        {
            return GetSectionView(formItem as FormSection);
        }
        else if (formItem is QuestionItem)
        {
            return GetTypedQuestionView(formItem as QuestionItem);
        }
        else
        {
            throw new NotImplementedException();
        }
    }

At this point the Model Bind bombs telling me it can't create an abstract class....

Server Error in '/' Application. Cannot create an abstract class. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: Cannot create an abstract class.

How do I get the model binder to get out of my way - I have provided the Action with the necessary model...?


Stab in the dark, but I think you need:

@foreach (var item in Model.Items){
   @Html.Action("GetFormItemView", "Question", new {formItem = item});
}


The problem is that the model binder does not know how to recreate your concrete class based only on the parameters. Look at the view yourself, and you will see that there is no way the Model Binder could know to create the correct class.

The model binder should be smart enough to walk the descendants of your base class and instantiate the right one, but unfortunately, it's not. There are probably edge cases that make this unreliable.

The easiest solution is to create seperate actions for each concrete model type. More complex solutions exist, you can check this question for examples.

0

精彩评论

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

关注公众号