MVC Snippets: must be a reference type in order to use it as parameter 'TModel' in the generic type or method 'System.Web.Mvc.ViewUserControl'

Recently I have been playing with ASP.NET MVC, in particular I have been building myself a new website. I thought it might be good to post any peculiar things / lessons I learn during this build. Tonight I stumbled across one of these lessons.





When you strongly type a view or partial view the type must be a reference type. Otherwise this means you get a HttpCompilation Error: "your data type" must be a reference type in order to use it as parameter 'TModel' in the generic type or method 'System.Web.Mvc.ViewUserControl'. Initially I couldn't figure out what this meant as I was passing my type through, it existed etc. However it was then I realised I had declared my type as a struct not a class.





If you are unsure of the difference between a class and a struct I recommend looking it up, the gist of it is that a class is a reference type and a struct isn't. As a struct isn't a reference type you can save memory due to it not having to allocate additional memory for referencing each object, this is great for short structures, but not for models in ASP.Net MVC


After changing my type to a class all was sorted and my view could compile again. A lesson learned, one of many I am sure ;)

Comments

Popular posts from this blog

WebUSB - An unexpected update...

Can you use BuildRoot with Windows Subsystem for Linux......

DotNet CLI , private NuGet feeds and Linux...