MVC返回View不调用控制器

Cra*_*aig 2 asp.net-mvc asp.net-mvc-4

我对MVC非常陌生,但我正在与一个可能非常基本和明显的问题作斗争.

在我的HomeController上,我有:

[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();
}
Run Code Online (Sandbox Code Playgroud)

当我启动我的应用程序时,此代码运行.

该页面作为登录屏幕的链接.

<div>
    @Html.ActionLink("Login", "ShowLoginScreen")
</div>
Run Code Online (Sandbox Code Playgroud)

页面加载,用户登录.

加载登录cshtml文件,用户输入用户名/密码:

<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>
Run Code Online (Sandbox Code Playgroud)

单击Login时,它会调用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();
        }
Run Code Online (Sandbox Code Playgroud)

代码运行,它返回到Index,但是Home Controller中用于'Index'的方法不会运行.页面刚刚在我的"公共ViewResult索引()"被调用时没有任何断点而被渲染.

谁能告诉我哪里出错了?

Joh*_*n H 5

这是因为您只是返回视图的输出:

return View("Index");
Run Code Online (Sandbox Code Playgroud)

这实际上不会调用控制器操作,它只是返回视图.要做你想做的事,你需要使用RedirectToAction:

return RedirectToAction("Index");
Run Code Online (Sandbox Code Playgroud)

  • @Craig - 返回视图("ViewName")仅用于视图名称与控制器名称不匹配的情况,或者您希望显式调用视图名称...只是因为.根据经验,只要你有一个不是AJAX的POST动作,就可以使用RedirectToAction("action").这是PRG中的R(后 - >重定向 - >获取) (2认同)