Introduction
In this article we will see how to work with user controls in ASP.Net MVC. Already all of you know how to create user controls i.e. ascx and use them in an ASP.Net web page but in the ASP.Net MVC framework this kind of stuff is different. As usual we can create user controls but instead of registering tagprefix in an ASP.Net page we have to render this user control in ASP.Net MVC. In this article we will see various ways of returning user controls in ASP.Net MVC.
Create User Controls and use at design time in ASP.NET MVC
All of you are familiar with user controls in ASP.Net so I'm assuming that you know how to create user controls but we will see the same user controls creation in MVC. In this section we will create one login status control to display the login status of the user.
Step 1:
Start a new ASP.Net MVC web Application. Add a new master page in the Views/Shared folder called SiteMaster.master. On this master page we will show the loginstatus user control but we don't have one so right-click on the shared folder by selecting add new item and select MVC3/2 user control and provide the name as LoginStatus.
Step 2:
Now we have a master page as well as a user control; now paste the following code into you user control source view to display the login status.
<%
if (Request.IsAuthenticated) {
%>
Welcome <strong><%: Page.User.Identity.Name %></strong>!
[ <%: Html.ActionLink("Logout", "Logout", "Home") %> ]
<%
}
else {
%>
[ <%: Html.ActionLink("LogIn", "Login", "Home") %> ]
<%
}
%>
In the above markup we have two action links; one for login and another for logout. Here we are checking that if the user is authenticated then show logout and show the user name else show the login which redirects to login page. For login and logout you can check my previous article Custom Login in ASP.NET MVC . In this article we will see how to use the user controls.
Step 3:
Now we have our user controls and we can show this LoginStatus control on our master page so let us keep on the master page like below.
<div id="loginstatus">
<%Html.RenderPartial("LoginStatus"); %>
</div>
In the above markup I'd kept one div tag inside the div tag; we have written the Html.RenderPartial method which will render our user control on the master page now. In ASP.Net you need to register one tagprefix and then use the user control by tagprefix registered but in ASP.Net MVC using simple Thml.RenderPartial we can use the user control.
Render User Control at Runtime On Modal Popup
On various sites we see login, registration, contact us forms are designed as only modal popup and we are taking the input from those windows. For popup you can see my previous article Popup Windows in ASP.NET MVC In this article we will create one Registration popup to register the user so lets create.
Step 1:
First you need to create one user control so just create user control name with RegisterControl and one modal called RegisterModel.
Step 2:
Paste the following code in RegisterModel class.
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
Step 3:
Now we are ready with RegisterModel; now we can design our registercontrol so design it by pasting the code given below.
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") %>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email) %>
<%: Html.ValidationMessageFor(m => m.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password) %>
<%: Html.ValidationMessageFor(m => m.Password) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.ConfirmPassword) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.ConfirmPassword) %>
<%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
</div>
<p>
<input type="submit" value="Register" onclick="close();" />
</p>
</fieldset>
</div>
<% } %>
In the above markup we are creating some input fields only; nothing to discuss here.
Step 4:
Still now we have a registercontrol and a modal; now we have to open the modal popup window to display our RegisterControl to open a popup; you can go through this article Popup Windows in ASP.NET MVC Now on your master page put one button which will open the popup window and your controller; write the following action to render our RegisterControl on the same popup window.
[HttpGet]
public PartialViewResult Register()
{
return PartialView("RegisterControl");
}
[HttpPost]
public ActionResult Register(UserControls.Models.RegisterModel model)
{
if (ModelState.IsValid)
{
return PartialView("RegisterSucess");
}
else
{
return PartialView("RegisterControl");
}
}
If you are clear about the modelpopup window opening then you can understand the above code. Here we have created two methods; one for rendering our RegisterControl on the modal popup and another one for registering the user.
In the first method we have simply written return PartialView() of our RegisterControl on the popup window. Here if we want to render our user control dynamically at runtime then we can use this method to do it. In the second method you can write your own logic to register and can return a success message to thye user on the same popup. Then using the simple script on RegisterSuccess control you can close the widow.
Conclusion
Using simple methods, we can use the user controls at design time as well as dynamically on runtime.