I am spending some time playing and loving the new MVC framework Scott Guthrie, Phil Haack, Hanselman, and crew are working on. Overall I am very excited about this technology and my hat is off to everyone involved.
Most of the examples out there use code in the ASPX view page to build the view, but I am a strongly typed kinda guy and I just can’t live without my user controls for rendering UI. This lead me to find an obtuse little bug in the designer.
I realize this is a trite detail and will likely be fixed in a future release, but I just wanted to drop this out there because it was quite frustrating for me for awhile.
When you create a new ViewPage via the Add > New Item > MVC View Content Page it created the typical ASPX and the code behind *.aspx.cs file. Then when you drop or declare a control on your ASPX page, the control is not declared in the code behind, making it impossible to bind to. We expect the control to be declared in the partial class *.aspx.designer.cs as is typical for a WebForm, but no such file is generated.
That’s ok, you can add your own partial class and Visual Studio sees it as a designer file. Do this before you add controls to your ViewPage and those controls will get auto-declared for you.
In the image below, I have added a partial class for my List page, but not for my Detail page.
The following code is the code I put into the file.
1: namespace MvcApplication.Views.Product {
2:
3: public partial class List {
4:
5: }
6: }
After dropping a literal onto my ViewPage and re-opening my designer class code file, this is what I find.
1: namespace MvcApplication.Views.Product {
2:
3:
4: public partial class List {
5:
6: /// <summary>
7: /// _categoryName control.
8: /// </summary>
9: /// <remarks>
10: /// Auto-generated field.
11: /// To modify move field declaration from designer file to code-behind file.
12: /// </remarks>
13: protected global::System.Web.UI.WebControls.Literal _categoryName;
14: }
15: }
Smooth as butter.
I noticed this issue a few weeks ago and it is definitely a bit of an annoyance. ScottGu posted a comment to my blog saying that it was in fact a bug in the MVC templates shipped in the CTP and mentioned an even easier way to fix this than the method described above. Check it out:
http://www.squaredroot.com/post/2007/12/MVC-Bug-Broken-Codebehind.aspx
Posted a permanent fix in the form of updated template files here:
http://www.squaredroot.com/post/2008/01/MVC-Template-Fix.aspx
Nice job, Troy. Thank you for this. Definately a better way to get around thi one.