0 Comments

Hello my english speaking visitors! As you maybe noticed, this blog is on croatian language, but just for your reading pleasure, this post is readable for more than 100 croatian speaking asp.net devsWinking smile

Now, back to the subject! Today is found nice link on www.asp.net home page, about using more than one model for MVC view, check it out here: http://honestillusion.com/blog/2013/11/11/Using-a-second-model-object-in-an-aspnet-mvc-view/

This will be my (short) take on this subject, offering yet another approach. We all know that MVC view can receive just one model type, that’s later available with @Model, and stuffing additional data to ViewBag is, or lets say, feels just wrong. And we’re to lazy to write a class that encapsulates all the types we need, as properties.

We can use (drum roll), yes, you are right my dear reader, TUPLE data structure! Someone may ask, what the heck are you talking about!? And you would give him some link like this one; http://www.dotnetperls.com/tuple or this one http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx and he would see how Tuple is nice and useful data structure, present in .NET from version 4 (I think, or 3. Or maybe 3.5. I don’t know)

So, without further ado, let’s see some code. Like controller:

And the view:

I’ll not show you my model code, because those are just plain old classes. Nothing interesting there.

And that’s the whole science with this technique! Just encapsulate as many types you want inside Tuple data structure, specify Tuple signature in view, and you get all the intellisense beauty in your Razor view!

Downside of this approach would be, let me think, maybe this: you can’t really tell what’s Model.Item1 and Model.Item2 just by looking at it, if you send tuple with two items of the same class it’s hard to tell which one you need to use, you brake concept ‘one view one model’ (I just invented this concept, but you get the point), etc. So, use it wisely, because with great power comes great responsibility (think about poor junior dev who will need to maintain your app few years from now)!