Creating Strongly-Typed Views in ASP.NET MVC Beta
Posted by Jason on December 5, 2008 at 12:42 pm
One of the big problems with the early adoption of any framework is the documentation. No books are released yet, if they are ever going to be, and so turning to Google is your best bet. In fact it’s your only option and my own preference is using Google over books anyway.
But frameworks change during development and you come across the issue that all of the top hits for your query are based on previous versions. When that previous version did it differently you’re stuck! I had this problem today when trying to create strongly-typed views. I love strongly-typed anythings, but I’m just a sucker for having a project that is more likely to work when another developer makes an edit and doesn’t bother fully checking the effects of their changes. It’s another safety net, and I’m a sucker for safety nets as well.
So, this is how I did it in bite-sized chunks. First the controller function:
-
public ActionResult Index()
-
{
-
var ContentObject = new ContentClass()
-
return View(ContentModel.Load(ContentObject));
-
}
Next I created a new view by right-clicking the above method (bear in mind that I’m using Visual Studio 2008) and checking the ‘Create a strongly-typed view’ before entering the full name of the object type (ContentClass). That produces an aspx.cs which looks something like this:
-
public partial class Index : ViewPage<ContentClass>
So far so good, but where I really came unstuck was actually using this in the view. Turns out it’s simpler than ever. All you need to use is the ViewData.Model parameter, which is automatically typed to whatever you set the view up as previously:
-
<%
-
foreach (var portfolio in ViewData.Model.Portfolios)
-
{
-
%>
-
<p><%= portfolio.ID %></p>
-
<%
-
}
-
%>
All that I have to do now is pass that through to a UserControl. I’m assuming I can strongly-type those as well. We shall see.