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
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.