简体   繁体   中英

User Control in ASP.NET MVC 5

I'm trying to create User Control in ASP.NET MVC 5. The control name is LoginUserControl.ascx and saved in Shared folder under Views. I'm trying to call the user control in the _Layout.cshtml but it is giving error? Please suggest the right way to do it.

.ASCX Code :

    <%@ Control Language="C#" 
    AutoEventWireup="true"
    CodeBehind="LoginUserWebControl.ascx.cs" 
    Inherits="TestApp.Views.Shared.LoginUserWebControl" %>

<%
    if (Request.IsAuthenticated) {
%>
        Welcome <b><%: Page.User.Identity.Name %></b>!
        @Html.ActionLink("Log Off", "LogOff", "Account") 
<%
    }
    else {
%> 
        @Html.ActionLink("Log On", "LogOn", "Account") 
<%
    }
%>

Adding in Layout.cshtml

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
       <li>@Html.ActionLink("Home", "Index", "Home")</li>
       <li>@Html.ActionLink("About", "About", "Home")</li>
       <li>@Html.ActionLink("Contact", "Contact", "Home")</li>   
       <li>@Html.Partial("LoginUserWebControl")</li>                
     </ul>

Error:

The view at '~/Views/Shared/LoginUserWebControl.ascx' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl. Blockquote

Your LoginUserWebControl.ascx.cs must derive from the ViewUserControl like so:

partial class LoginUserWebControl : System.Web.Mvc.ViewUserControl
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM