rigamonk
rigamonk

Reputation: 1181

MVC 5 - Would like to have page display if not logged in

I am using the following code to display a login form (Login.cshtml) when the user is not authenticated and the main page when the user is authenticated: Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>

    <!-- META SECTION -->
    <title>Coalesce</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <!-- END META SECTION -->
    <!-- CSS INCLUDE -->
    <link href="~/Content/Template/css/theme-default.css" rel="stylesheet" />
    <!-- EOF CSS INCLUDE -->
</head>
<body>
     @if (!Request.IsAuthenticated) {
            <div class="login-container">
                @RenderPage("~/views/Account/Login.cshtml")
            </div>
            RenderBody();
        }
        else {
                ...Normal page here
}
</body>
</html>

The Login.cshtml looks something like this:

<!DOCTYPE html>
<html lang="en">
<body>
     ...Login controls
</body>
</html>

I am using OWIN and everything wroks fine, but when I hit the login page portion, it only displays on half the screen, so half is the login page, and the bottom is white.

I've tried RenderPartial and a few other things in the authentication check, but I get get the login page to display on the full browser window. I'm sure its the way that @if (!Request.IsAuthenticated) { @RenderPage("~/views/Account/Login.cshtml") RenderBody(); } is constructed, but i'm currently stumped.

Upvotes: 0

Views: 1836

Answers (1)

Peter B
Peter B

Reputation: 24280

I've never seen this approach before, but in any case (assuming it works) Login.cshtml should not contain <!DOCTYPE>, <html> and <body> tags because it will be rendered inside Layout.cshtml, which already contains these tags.

The approach that I am familiar with is: let a Controller, or even a global ActionFilter, check if one is logged in. If not, show View("Login"), or redirect to /Home/Login. Then let Login.cshtml be rendered using Layout.cshtml (which contains no login logic) - and not the other way around which is what you seem to be trying.

Controllers/HomeController.cs example

public ActionResult Index()
{
    if (!Request.IsAuthenticated)
        return View("Login");
    // Add normal flow here
}

Upvotes: 1

Related Questions