lundi 1 juin 2015

Pass anonymous type as model in MVC 3 Partial View

I am refactoring an MVC 3 application, and moved a set of similar items into a partial view so I can keep that template DRY. Since the pieces don't all have the exact same properties, I am creating anonymous types like this:

var model1 = new { Description = "description 1", Message = "message 1" }

and passing them to the partial view like so:

@Html.Partial("_Partial", model1)

The partial view is then attempting to render certain blocks based on existence of a specific property, i.e.

@if (Model.Description != null) { @Model.Description }

My issue is that even though I can see and navigate the Model object in the watch window during execution, I get a RuntimeBinderException in the if test that states 'object' does not contain a definition for 'ShowApplied'. I can obtain the values through reflection by calling (Model.GetType().GetProperty("ShowApplied").GetValue(Model)), but would much rather use the format shown in my code sample.

I have been unable to find a clean solution; how can I pass an anonymously-typed object to a partial view and access its properties directly? I feel like there is something simple I'm missing...

Aucun commentaire:

Enregistrer un commentaire