4

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?

1 Answer 1

7

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Solved. I'll need to work out when 'return View("Index")' would ever be used then. Thanks!
@Craig - Return View("ViewName") would only be used in a case where the view name does not match the controller name or you wanted to explicitly call the view name...just because. A rule of thumb, any time you have a POST action that is not AJAX, use RedirectToAction("action"). That is the R in PRG (Post -> Redirect -> Get)
@Craig No problem, and Tommy's on the money here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.