Creating Views with no Code Behind
You can create views without having any of the code-behind files by using the ResourceView<T>
base class.
To use a ResourceView
, you have two options. You can create New OpenRasta View from the Add New Item context menu (if using the Visual Studio integration).
If you’re not using the VS integration for some reason, you can also create a new WebForm
longhand and edit it with these three steps:
- Delete the code-behind .aspx.cs and .aspx.designer.cs
- Remove the
<form>...</form>
tags from the<body>
. - Edit the
<%@ Page ... %>
directive by removing the AutoWireup and CodeBehind attributes and change the Inherits attribute toOpenRasta.Codecs.WebForms.ResourceView<TypeOfResource>
. When you are finished, your<%@ Page ... %>
directive should look like this:
<%@ Page Language="C#" Inherits="OpenRasta.Codecs.WebForms.ResourceView<TypeOfResource>" %>
The !ResourceView exposes a Resource property that is strongly-typed to the generic argument to the !ResourceView. You can use this property to access instance members of your Resource. For example, if you have a
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
and set your .aspx
view to inherit from ResourceView<Person>
, you can access the members of your resource with the Resource property like so:
<%@ Page Language="C#" Inherits="OpenRasta.Codecs.WebForms.ResourceView<Person>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Person named <%= Resource.LastName %></title>
</head>
<body>
<div>
<p>This is the page of <%= Resource.FirstName %></p>
</div>
</body>
</html>
Intellisense will provide the properties of Resource
for you.
To keep your views clean, you should also add these namespaces to your web.config
(again, you won’t need to if using a project created with the VS integration):
<pages pageParserFilterType="OpenRasta.Codecs.WebForms.OpenRastaPageParserFilter">
<namespaces>
<add namespace="System.Collections.Generic"/>
<add namespace="OpenRasta.Web"/>
<add namespace="OpenRasta.Web.Markup"/>
<add namespace="OpenRasta.Codecs.WebForms"/>
<add namespace="MyRestApplication.Resources"/> <!-- replace with your project namespace -->
</namespaces>
...
</pages>
In short, cleanliness. Why code what you don’t need to? When you can represent all you need to with ResourceView<T>
there’s no need for a couple of extra files cluttering your source control system.