using dynamic as type of MVC strongly typed view

自作多情 提交于 2020-01-26 03:28:33

问题


I have a page for creation of dynamic entities.

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
...

I have two actions:

public ActionResult Create()
  {
      dynamic model = ...
      return View(model);
  }

[HttpPost]
public ActionResult Create(dynamic(1) entity)
  {
     ...      
  }

Well, the problem is that the entity comes empty from the page. If I change dynamic in (1) for the real type it works fine.


回答1:


I'm not 100% on this, but I think the problem is that the default model binder has no idea what to do with a 'dynamic' type, since it doesn't have any defined properties to reflect over. You'd need to write your own model binder that would use the form input names instead, which is dangerous/unreliable because the form can be modified on the client side.

I've explored dynamically-typed ViewPages before (here on SO actually: Dynamic typed ViewPage), and I've come to the conclusion that it really doesn't give you anything in most situations. At least, not yet (MVC 3+ could be different story).

And here's some notes from Phil Haack on the matter: http://haacked.com/archive/2009/08/26/method-missing-csharp-4.aspx



来源:https://stackoverflow.com/questions/2849872/using-dynamic-as-type-of-mvc-strongly-typed-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!