views:

236

answers:

2

I'm looking to get rid of the code-behind for a control in my WebForms 3.5 application. Again bitten by the bug of how it's done in MVC, I'd like to get a step closer to this methodology by doing:

<%@ Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>

This gives me the parser error you'd expect, so I remembered back to when this was an issue awaiting a fix in the MVC Preview, and changed it to:

<%@ Control Language="C#" Inherits="Core.DataTemplate`1[[Models.NewsArticle]]" %>

But this doesn't work either! How is it that the MVC team were able to harness this ability? Was it something special about the MVC project type rather than the latest VS2008 Service Pack?

Short of giving up and requiring future templates to have code-behind files, what are my best options to get this as close to the generic user control method as possible?

A: 

With WebForms you lose pretty much everything that makes them useful without a code behind page, because then VS can't auto generate the designer file that holds the actual definitions for all your runat="server" controls.

What you can do is have a common base page class, and make that generic:

public class DataTemplate<T> : Page {
    public T Model {get;set;}
}

public partial class MyCodeBehindClass : 
    DataTemplate<Models.NewsArticle> {
    ...
}

This would allow all the drag-drop component stuff that WebForms does to work unhindered, while also allowing you to access a strongly typed model on the page:

<%@ Control Language="C#" Inherits="MyCodeBehindClass" %>

<% foreach( var item in Model ) { %>
    <!-- do stuff -->
<% } %>
Keith
Ah sorry, my question probably wasn't clear on this, but I already have a DataTemplate<T> : UserControl class that I'm trying to use within the custom ASCX, and avoid using the partial class.
tags2k
Ahh, but why then keep any of the WebForms stuff at all? Why not go for MVC as you won't be able to use any WebForms components without the VS generate partial class?
Keith
This is an existing WebForms application that I'm trying to tidy up as much as possible, so I can't change the whole architecture. Most of the front-end generation is abstracted up so the only thing I need to worry about maintaining is MasterPages and these templates where required, which don't need any of the WebForms bits.
tags2k
+2  A: 

Well, it appears like I've managed to do it. After looking at the PageParserFilter implemented by the MVC team for ViewUserControl<T>, I was able to construct something similar for my own DataTemplate<T> purposes. Sweet. I can now use the line:

<%@ Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>

And, without any code behind file, it parses! I'll report back if I find that I've broken something else in the process!

tags2k