Search code examples
asp.netasp.net-mvcexpando

EditorForModel and DisplayForModel don't work on Expando objects


Or at least, they don't do what I was expecting. My Action method looks like this:

    Function Test() As ActionResult
        Dim model As Object = New ExpandoObject()
        model.FieldA = 123
        model.FieldB = "This is a string"
        model.FieldC = DateTime.Now

        Return View(model)
    End Function

and the view looks like this:

@ModelType Object
@Html.DisplayForModel

I was expecting it to produce the same thing you'd get if the model were a real object with those fields, but instead I get this:

[FieldA, 123][FieldB, This is a string][FieldC, 3/29/2012 12:10:24 PM] 

EditorForModel does the exact same thing. Is this the correct behavior, and what's the best way to implement the behavior that I'm looking for?


Solution

  • Yes, this is the correct behavior. Default metadata provider (DataAnnotationsModelMetadataProvider) uses reflection to get model information and that is the reason you get this result.

    I would suggest to create a custom metadata provider that will work correctly with dynamics. Try to inherit from this class - http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelmetadataprovider.aspx.