Home > DeveloperSection > Articles > User Control in ASP.NET MVC

User Control in ASP.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 12936  View(s)
Rate this:

User Control in ASP.NET MVC

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 Control 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 Control 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 Control in ASP.NET MVC

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

User Control in ASP.NET MVC

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


Good

By Munikumar G on   5 years ago
This is very good for us.............

Small request

By Munikumar G on   5 years ago

I need Asp.net menu control working dynamically in app.

Please help me............

Emailid:gulurumunikumar@gmail.com


Don't want to miss updates? Please click the below button!

Follow MindStick