Pass Multiple Strongly Typed Models to Views in ASP.NET MVC

I had a requirement recently for a view with multiple required Models. The view was mainly a list of one type of objects, but also had to grab a couple of pieces of information from another object. The obvious ways to do this would be to:

  1. Create a ViewModel specifically for this view that simply contained the two models I needed, or
  2. Use ViewData to get my single object to the view

I didn’t like either of these options – creating a ViewModel to hold two pieces of data seemed like overkill, especially for a view that doesn’t require any form interaction. And Using ViewData is not a good choice since it uses Magic Strings and is not strongly typed.

Instead, I used a construct that I hadn’t had a chance to use before – the Tuple! This allowed me to create a strongly typed object to use as my Model without having to create a whole new class for it:

public ActionResult GetItemList()
	var itemList = _repo.GetListOfItems();
	var otherItem = _repo.GetOtherItem();
	return View(new Tuple, Type2>(itemList, otherItem));

The only drawback to this is that in your view you must refer to your Model objects as Model.Item1 and Model.Item2. For a simple case like this, the tradeoff is worth it to me – simple, quick, clean and type-safe!

Posted Wednesday, May 11th, 2011 under .NET.

Leave a Reply