It’s common in ASP .NET Web Forms to create user controls that encompass frequently accessed user interface components. WebForms user controls can be created which allow setting of properties, customization, and placement on any aspx web form for display of content. However, with ASP .NET MVC (Model View Controller), the creation of user controls typically follows a slightly different approach. In particular, without the usage of Session or the traditional WebForms event model, it can be difficult to create the types of user controls many WebForms developers are familiar with. While you can certainly embed WebForms user controls within an ASP .NET MVC web application, it could be considered good practice to follow the traditional MVC architecture with the creation and usage of partial view user controls.
In this tutorial we’ll create a gradient color box user control with ASP .NET MVC 3 and Razor by using a Partial View. We’ll display our ASP .NET MVC 3 Partial View user control through a simple client-side call and via a server-side call, allowing for initialization of the user control in code. For extra customization, we’ll also demonstrate how to configure a property on the user control, prior to display.
An MVC User Control Without Initialization
Including a user control via a partial view in ASP .NET MVC 3 can be performed by using the Html.Partial helper method to render the user control. An example appears, as follows:
The above tag, included within our Index.cshtml view page, simply embeds a partial view to be rendered within the page. The partial view is actually a view on its own, complete with its own ColorBlockUserControl.cshtml view page file. The partial view is simply rendered inline within the parent page. In this manner, we can create a basic user control in an ASP .NET MVC 3 web application with Razor.
An MVC User Control With Server-Side Initialization
Taking it one step further, we can provide server-side initialization of our partial view user control in ASP .NET MVC 3 by using the Html.RenderAction helper method. This allows us to programatically setup the user control with any required data, prior to display.
It’s important to note the format of the razor syntax for including the RenderAction helper method. We enclose the call within brackets in order to render properly. Upon display, ASP .NET MVC 3 will execute the action method “InitializeUserControl” on the current view controller, which in turn, will perform any initialization and return a PartialView as a result.
The Whole Page and Nothing But the Page
To begin creating our gradient color box user control in ASP .NET MVC 3 with Razor and a partial view, we’ll layout how we’ll include the partial view tags within our page. Our HTML and Razor code for Index.cshtml will appear as follows:
Notice in the above code, we’ve created our main page to be strongly typed to the model HomeModel. This is just to demonstrate that the main view and the partial view (user controls) can have different models, allowing you to separate concerns of data processing between the hosting page and child views or controls. The type HomeModel is a simple class with a string, displayed towards the top of the page. Notice that we’ve also included two calls to display our user control. The first call will render the control without server-side initialization, while the second call will first pre-process and initialize the partial view and finally render it.
A Simple Controller for our Page
With the HTML for the parent page defined, we can add a Controller class for processing the view. Our controller will simply return a new instance of the HomeModel, which is what our page is strongly bound to, allowing us to display the welcome text. We’ll also provide the method “InitializeUserControl”, which is where we will perform any setup of the user control prior to display. The controller code appears, as follows:
public class HomeController : Controller
Notice in the initialization method, after setting up the model, we simply return the PartialView itself and pass in the required model. In this way, the rendering partial view will utilize the model and display the contents appropriately.
Before going further, we’ll define our ASP .NET MVC models which are used within the parent and child partial view user controls. HomeModel will simply hold a string for the parent page, while ColorModel will hold properties required for drawing the gradient color box.
The Simple HomeModel
public class HomeModel
public class ColorModel
The Child View is Where Things Get Interesting
We can now create the view page for our actual user control. Since our user control is really an ASP .NET MVC 3 partial view, we can define the view in the same way as we would any other:
Notice in the above code, we’ve bound our partial view to the strong type ColorModel. Our ASP .NET MVC 3 partial view (user control) will deal exclusively with the ColorModel type. It will provide a simple form for entering parameters to populate the model. It will also execute the ColorModel to draw a gradient color box within the MVC user control.
We’re also taking advantage of the Microsoft helper method Ajax.BeginForm (which, in ASP .NET MVC 3, uses the jQuery AJAX form tags for optimized results). Since our partial view needs to display and update the contents of a page inline, we’ll need to use the MVC Ajax form tag. Otherwise, our page would be redirected to the action method, erasing the prior contents.
No Two Controls Are the Same
It’s important to note the UpdateTargetId property of the Ajax.BeginForm tag, which is where we’ll draw the results from our user control. The UpdateTargetId specifies the ID property for an HTML div or span tag, which will contain the results of the form submission. Since we might include multiple user controls on one page, we’ll want to uniquely define each div tag. We provide this functionality through the Id property of the ColorModel, which is actually nothing more than a static incremental integer.
The Partial View Can Have Its Own Controller Too
In the above ASP .NET MVC 3 Razor partial view, you may have noticed that we’re posting the form to a specific action method on a different controller than the parent. In this manner, we can provide a separate distinct controller for our MVC user control. Additionally, we can lock down the controller to only accept the POST request from the ajax form, and not allow direct navigation (since only the calling user control form would access this method). Our MVC partial view user control can be defined, as follows:
public class ColorBlockUserControlController : Controller
In the above code, we’re using a helper class, ColorManager, to perform the actual drawing of the gradient color box within the user control. We’ll return a block of HTML div tags as the result to the AJAX call, which will dynamically update the parent view page with the resulting color box. The action method DrawColor() is called by the ajax form submission, performing a seamliness inline update of the HTML content with the ASP .NET MVC partial view user control’s result.
Passing Parameters to the User Control
While ASP .NET Web Form user controls exposed public properties of the control’s code-behind as parameters that could be set within the ASPX, ASP .NET MVC 3 provides the ability to pass query string parameters to the action method, allowing for configuring of the partial view or user control content. We can update the user control client code to pass a parameter in the query string as follows:
Similarly, the controller code would require the property to be added as follows:
public ActionResult InitializeUserControl(bool fadeToBlack)
Taking the usage of the ASP .NET MVC 3 partial view user control even further, we can replicate the same user control multiple times on the same page. We’ve provided this functionality by providing a unique div ID value for each user control’s associated ajax form. In this manner, upon submission of the ajax form, the associated div tag will update with the appropriate color gradient box. Multiple ASP .NET MVC 3 partial view user controls can be added by including the same tag multiple times:
@Html.Partial("UserControls/ColorBlockUserControl", new ColorModel())
Download @ GitHub
You can download the project source code on GitHub by visiting the project home page.
ASP .NET MVC 3 partial views provide the ability to implement MVC compatible user controls, ideal for isolating common user interface components and compartmentalized design. By using the ASP .NET MVC helper methods for Partial and RenderAction, developers can supply user controls that may be initialized inline within the client view or by server-side code, providing flexibility and re-use of user interface code.
About the Author
This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.Sponsor Me