Introduction
This article explains how to create a User Control in the Web API. We add a "MVC4 View User Control (ASPX)" in which we create a link that calls the action method from the "Controller".
Procedure for creating the User Control in the Web API.
Step 1
Create an API application as in the following:
- Start Visual Studio 2012.
- From the start window Select "Installed" -> "Visual C#" -> "Web".
- Select "ASP.NET MVC4 Web Application" and click the "OK" button.
- From the "MVC4 Project" window select "Web API".
- Click the "Ok" button.
Step 2
Now we add a User Control named "UserControlAPI.ascx".
- In the "Solution Explorer".
- Right-click on the "Shared folder", select "Add" -> "New Item".
- Select "Installed" -> "Visual C#" -> "Web".
- Select "MVC4 View User Control (ASPX)".
- Click the "Ok" button. It will be shown in the Shared folder.
Add the following lines of code:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%: Html.ActionLink("ClickMe","Display") %>
In this code "ClickMe" is a link and "Display" is an action method. When we click on the link "ClickMe", it calls the action method "Display" from the controller.
Step 3
Now in the "HomeController" we create an action method "Display". This file exists in the:
- In the "Solution Explorer".
- Spread the "Controller" folder.
- Select the "HomeController".
Add the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UserControlAPI.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public string Display()
{
return "<h3>This is the example of the User Control:</h3>";
}
}
}
Step 4
Now add a "View Page" "Index.aspx" in the "Home" folder.
-
In the "Solution Explorer".
-
Right-click on the "Home" folder then select "Add" -> "New Item".
-
Select "Installed" -> "Visual C#" -> "Web".
-
Now select "MVC4 View Page (ASPX)".
-
Click the "Ok" button.
Add the following code:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title>Index</title>
</head>
<body>
<div>
<h3><% Html.RenderPartial("UserControlAPI"); %></h3>
</div>
</body>
</html>
In the following code we use the "Html.RenderPartial" in which the "RenderPartial" method renders the "UserControl" (the .ascx file) using the "Html" helper, here the user control file is "UserControlAPI.ascx".
Step 5
Execute the application by pressing "F5". The output will be displayed like this:
Click on the link "ClickMe". It displays a message.