articles

Home / DeveloperSection / Articles / User Controls in ASP.NET MVC

User Controls in ASP.NET MVC

User Controls in ASP.NET MVC

Chris Anderson 21250 08-Oct-2011

In this article I will explain how to create and render a User Control in ASP.NET MVC.

Create a User Control:

To create a user control you have to add a new item (MVC 3 View User Control (ASPX)) from an Add New Item template. You can change the name of user control as you want. Here I change it as UserControl.ascx.

User Controls in ASP.NET MVC

After adding the user control check whether your user control exists in Shared folder or not and if it not exists in Shared folder then cut the UserControl.ascx from the other locationand paste it into Shared folder.

User Controls in ASP.NET MVC

Here in a UserControl file I simply create a link that call a ShowData() action method from the controller.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>


<%: Html.ActionLink("Home","ShowData",) %>

 

Create a ShowData action in a Controller that returns a formatted string.

using System.Web.Mvc;


namespace UserControlDemo.Controllers
{
     public class HomeController : Controller
    {
         public ActionResult Index()
         {
            return View();
         }
         public string ShowData()
        {
            return "<h3>Page Under Construction</h3>";
        }
    }
}

 

After creating a user control you have to render it in your view. Here in an index view I am rendering a User control:

<html>

<head runat="server">
     <title>Index</title>
</head>
<body>
     <div>
         <h3><% Html.RenderPartial("UserControl"); %></h3>
     </div>
</body>
</html>

 

After render a User Control you can see the output as below:

User Controls in ASP.NET MVC

When you click on Home link it will display a message as below:

User Controls in ASP.NET MVC

Thank you for reading this article and I think this will help you a lot.


Updated 04-Mar-2020
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By