以我的子操作方法的方式绑定 MVC3 模型
我正在使用 MVC3 并尝试利用子操作功能 @Html.Action()
所以我有一个具有以下内容的视图
@foreach (var item in Model.Items){ @Html.Action("GetFormItemView", "Question", item}); }
这调用了以下方法
[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(); } }
此时模型绑定炸弹告诉我它可以不要创建抽象类......
“/”应用程序中的服务器错误。 无法创建抽象类。 描述:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
异常详细信息:System.MissingMethodException:无法创建抽象类。
如何让模型绑定器摆脱我的干扰 - 我已经为操作提供了必要的模型......?
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...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在黑暗中刺伤,但我认为你需要:
Stab in the dark, but I think you need:
问题在于模型绑定器不知道如何仅根据参数重新创建具体类。亲自查看该视图,您会发现模型绑定器无法知道创建正确的类。
模型绑定器应该足够智能,可以遍历基类的后代并实例化正确的模型,但不幸的是,事实并非如此。可能存在一些边缘情况使其不可靠。
最简单的解决方案是为每个具体模型类型创建单独的操作。存在更复杂的解决方案,您可以查看此问题作为示例。
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.