Craig
Craig

Reputation: 18684

MVC return View not calling controller

I'm extremely new to MVC, but am battling with an issue that is probably very basic and obvious.

On my HomeController, I have:

[HttpGet]
public ViewResult Index()
{
    int hour = DateTime.Now.Hour;
    var reply = User.Identity.IsAuthenticated ? User.Identity.Name + " is Logged in!" : hour < 12 ? "Good morning" : "Good afternoon";
    ViewBag.Greeting = reply;
    return View();
}

When I start my application, this code runs.

The page as a link to a Login screen.

<div>
    @Html.ActionLink("Login", "ShowLoginScreen")
</div>

The page loads, and the user logs in.

The login cshtml file loads, and the user has a username/password to enter:

<body>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <p>Username: @Html.TextBoxFor(x=>x.Username)</p>
        <p>Password: @Html.TextBoxFor(x=>x.Password)</p>
        <p><input type="submit" value="Login"/></p>

    }
</body>

When clicking Login, it calls a method in my HomeController:

[HttpPost]
        public ActionResult ShowLoginScreen(Login login)
        {
            if (ModelState.IsValid)
            {
                var reply = new BasicFinanceService.UserService().Authenticate(login.Username,
                                                                               Security.EncryptText(login.Password));
                if(reply.Id != 0)
                    FormsAuthentication.SetAuthCookie(reply.Username, false);
                return View("Index");
            }
            return View();
        }

The code runs, it goes back to Index, BUT the method in the Home Controller for 'Index' doesn't run. The page just gets rendered without any breakpoint in my "public ViewResult Index()" being called.

Can anyone tell me where I am going wrong?

Upvotes: 4

Views: 5815

Answers (1)

John H
John H

Reputation: 14655

It's because you're simply returning the output of the view with:

return View("Index");

That doesn't actually invoke the controller action, it simply returns the view. To do what you want, you need to use RedirectToAction:

return RedirectToAction("Index");

Upvotes: 7

Related Questions