mmssaann
mmssaann

Reputation: 1507

return data to view using expandoobjects MVC4

I am just trying to learn expandoobjects in mvc4.

I have a model say

 pulic class A
 {
   public string FirstName{ get; set; }        
   public string LastName{ get; set; }
   public System.DateTimeOffset DOB {get; set; }
 }

say I have another model

 pulic class B
 {
   public string JobTitle{ get; set; }        
   public System.DateTimeOffset FromDate { get; set; }
   public System.DateTimeOffset ThruDate {get; set; }
 }

I have controllers for each model. Now I will have a single view to list all the items of either model 'A' or model 'B'.

I heard that we can achieve this using expandoobjects, I should be able to written list of items of model 'A' or model 'B' to that single view and that view should display its content. Im missing how to start with this using expandoobjects.

Can somebody give some start pls?

Upvotes: 0

Views: 159

Answers (1)

Slicksim
Slicksim

Reputation: 7172

I wouldn't even begin to try and do this, the amount of reflection work needed would be horrendous, a real maintenance nightmare

Set up a folder structure like this

-Views
    -Shared
         -EditorTemplates
              -TextBox.cshtml
              -SelectList.cshtml
              -DateBox.cshtml

In these editortemplates, setup the template as you wish it to be displayed, so add all the relevant styling or controls that you have developed in house. These will be your control templates.

Next, on each of your pocos, leverage the UIHint attribute, which will help Razor decide what template to use for each field.

So

public class A
{
   [UIHint("TextBox")]
   public string FirstName{ get; set; }   
   [UIHint("TextBox")]     
   public string LastName{ get; set; }
   [UIHint("DateBox")]
   public System.DateTimeOffset DOB {get; set; }
}

Now when editorformodel starts to select out it's templates, it should pick up your editortemplates and use those instead.

I'm not a fan of cluttering a poco with ui concerns, I much prefer cleaner pocos and specific views for clarity, however, I think will save you trying to work out what you need to output and use more of the templating features in mvc

Upvotes: 1

Related Questions