简体   繁体   中英

Passing IEnumerable<Object> to MVC view and casting to strongly typed object

I have a requirement to pass an IEnumerable<Object> to an MVC view and have the view cast this to a strongly typed object and display it accordingly.

This appears to be having a performance impact vs. passing it down as a IEnumerable of MyCustomObject.

foreach (var item in Model.Items)
{
    var current = (MyCustomObject) item;
    <p>@current.Submitted</p>
}

My questions are

  1. Should I cast the entire IEnumerable of Objects to IEnumerable of MyCustomObject?
  2. How can I improve the performance of this operation?
  3. If this is not good practice, what's the best way to pass a "variable" type for my Items collection, which could be a collection of any type of custom object?

Use a List pass this to the model, then it is strongly defined

Controller

public ActionResult Index(){

MyModel model = new MyModel();
model.list = //get list from source

return View(model);

}

Model

public List<MyCustomObject> list {get; set;}

Initially, you could use Cast on the entire collection:

foreach (var item in Model.Items.Cast<MyCustomObject>()){}

If your types will all inherit from a base type, say MyCustomObject, then your model should specify this, eg

public class MyViewModel<T> where T : MyCustomObject, new() 
{
    public IEnumerable<T> Items { get; set; }
}

You would need to ensure that any types you wished to add to your items collection inherited from the base MyCustomObject type

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