MVC返回View不调用控制器

 我的 发布于 2023-02-08 16:01

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

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

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

@Html.ActionLink("Login", "ShowLoginScreen")

页面加载,用户登录.

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


    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        

Username: @Html.TextBoxFor(x=>x.Username)

Password: @Html.TextBoxFor(x=>x.Password)

}

单击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();
        }

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

谁能告诉我哪里出错了?

1 个回答
  • 这是因为您只是返回视图的输出:

    return View("Index");
    

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

    return RedirectToAction("Index");
    

    2023-02-08 16:04 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有