Nov 11, 2008 / .net ~ mvc ~ asp.net
ASP.NET MVC - Losing the CodeBehind

Like some other people, I'm not really enjoying having code behind files in ASP.NET MVC.

As Tim Barcz points out, if you want to lose the CodeBehind and still have strongly typed ViewData.Model, you can do this:

<%@ Page Language="C#" 
           Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]"  %> 
<h1>Welcome <%= ViewData.Model.Username %></h1>

It's ugly, but it works!

What about another approach?

<%@ Page Language="C#" 
           Inherits="System.Web.Mvc.ViewUserControl"  %>
<% var Model = (LoginData) ViewData.Model; %>
<h1>Welcome <%= Model.Username %></h1>

Again, it's a kludge, but avoids playing with weird generic names :)


You may also like...