简体   繁体   中英

using dynamic as type of MVC strongly typed view

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM