Create and Consume A User Control in MVC

Introduction

This article explains how to create and consume a User Control in MVC. I hope you will like it.

Please see this article in my blog.


Background

Today I got the requirement to work with CellSetGrid. Since it is supported with our normal ASP.Net web pages alone, I was in a need to convert it to a user view control and consume it in MVC because my application is in MVC4. I have done it. So I thought of sharing it with you all.

Using the code

To do so, you need to use the following procedure.

Add a reference to your control DLL.

Create And Consume A User Control In MVC

Create And Consume A User Control In MVC

Add a new Web User Control.

Create And Consume A User Control In MVC

Create And Consume A User Control In MVC

Register your DLL reference.

  1. <%@ Register assembly="CellSetGrid2" namespace="OLAPControls" tagprefix="cc1" %>  

Place your control. 

  1. <div>  
  2.    <cc1:CellSetGrid2 id="csg2" runat="server" connectionstring="Data Source="Your DataSource"; Initial Catalog =Your DB Name"  
  3. cube="Your Cube Name" height="800px" width="1500px" />  
  4. </div>  
Change default namespace

Go to ADODMGrid.ascx.cs from the Solution Explorer.

Create And Consume A User Control In MVC

Change the namespace System.Web.UI.UserControl to System.Web.Mvc.ViewUserControl.

Create the Controller.

Create And Consume A User Control In MVC

Create a View.

Create And Consume A User Control In MVC

Please ensure that you have selected a partial view.

Create And Consume A User Control In MVC

Add the User Control to your View as in the following:

  1. @Html.Partial("ADODMGrid")  
  2. @* Here ADODMGrid is our user control name. No need to give its extension (ascx)*@  

So here we are add our new web user control to our view.

Add tagPrefix to your Web.Config

Last but the least, you need to add tagPrefix to your web.config file as follows.

  1. <controls>  
  2.    <add tagPrefix="cc1" namespace="OLAPControls" assembly="CellSetGrid2, Culture=neutral, PublicKeyToken=null" />  
  3. </controls>  
You need to add the preceding code under system.web –> Pages.

Now when look at your view, you can see your control there.

Conclusion

That is all. I hope you liked this article. Please share me your feedback.

Kindest Regards,
Sibeesh Venu


Similar Articles