gpt4 book ai didi

asp.net-mvc - MVC返回 View 不调用 Controller

转载 作者:行者123 更新时间:2023-12-04 02:09:00 25 4
gpt4 key购买 nike

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

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

谁能告诉我我哪里出错了?

最佳答案

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

return View("Index");

这实际上并没有调用 Controller 操作,它只是返回 View 。做你想做的事,你需要使用 RedirectToAction :
return RedirectToAction("Index");

关于asp.net-mvc - MVC返回 View 不调用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20734526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com