【问题标题】:MVC return View not calling controllerMVC返回视图不调用控制器
【发布时间】:2013-12-22 22:05:15
【问题描述】:

我对 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();
}

当我启动我的应用程序时,这段代码就会运行。

作为登录屏幕链接的页面。

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

页面加载,用户登录。

登录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>

点击登录时,它会调用我的 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();
        }

代码运行,它返回到索引,但主控制器中用于“索引”的方法没有运行。该页面只是在没有任何断点的情况下呈现在我的“公共 ViewResult Index()”中被调用。

谁能告诉我哪里出错了?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

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

    return View("Index");
    

    这实际上并没有调用控制器动作,它只是返回视图。做你想做的事,你需要使用RedirectToAction

    return RedirectToAction("Index");
    

    【讨论】:

    • 谢谢!解决了。我需要弄清楚什么时候会使用'return View("Index")'。谢谢!
    • @Craig - Return View("ViewName") 仅在视图名称与控制器名称不匹配或您想显式调用视图名称的情况下使用......只是因为。根据经验,任何时候你有一个不是 AJAX 的 POST 操作,都使用 RedirectToAction("action")。那就是 PRG 中的 R (Post -> Redirect -> Get)
    • @Craig 没问题,Tommy 在这里赚钱。
    猜你喜欢
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多