ASP.NET MVC and Accessing Server Controls in CodeBehind

If you are new to MVC in ASP.NET, it is only natural that your first attempt at using it will involve the use of server controls. If you create a blank ASP.NET MVC Website and add a Repeater Control to the Index View of the Home Controller:


 


ASP.NET MVC Tutorial 


 


and try to access it from the codebehind, you might freak out a bit that you won’t be able to access the Repeater Control.


The problem is that we have all been spoiled by the designer file that is normally associated with Web Application Projects. As you drop server controls on the form, controls are automatically declared in a partial class in the designer file. If you check out your ASP.NET MVC solution, you will notice the absence of these designer files. Adding them is as simple as right-clicking on the view file and choosing “Convert to Web Application“.


 


ASP.NET MVC Conver to Web Application 


 


 


This will add the designer file associated with the view.


 


 


 


 


The Repeater Control will now be declared in the designer file:


 

public partial class Index {

/// <summary>
/// Repeater1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Repeater Repeater1;
}


 


and available in the code-behind file.


 



 


 


Hopefully this helps.


 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

3 Responses to ASP.NET MVC and Accessing Server Controls in CodeBehind

  1. Troy Goode says:

    ScottGu has confirmed that it is a template bug that will be fixed in the next CTP. You may want to take a look at my recent post containing a template fix that automatically creates the designer files for you. No more right-clicking and selecting “Convert to Web Application”!

    http://www.squaredroot.com/post/2008/01/MVC-Template-Fix.aspx

  2. Chris Martin says:

    Besides not have postback and viewstate, isn’t this just opening one up to the problems of webforms? Don’t we want our controllers independent of our views?

    This guy’s confused…. ;)

  3. Jimmy Bogard says:

    Just curious, does this change the .csproj file?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>