SIGN UP MEMBER LOGIN:    
ARTICLE

Working With User Controls in ASP.NET MVC

Posted by Krishna Garad Articles | ASP.NET MVC with C# January 23, 2012
In this article we will see how to work with user controls in ASP.NET MVC.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks Guys

Posted by Krishna Garad Jan 24, 2012

Its a useful and good article.

Posted by Stephen Johnson Jan 24, 2012

Thanks,this article is considerable

Posted by Jimmy Underwood Jan 24, 2012

Thanks for the explain the user control

Posted by Arjun Panwar Jan 24, 2012
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor