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索引()"被调用时没有任何断点而被渲染.
谁能告诉我哪里出错了?
这是因为您只是返回视图的输出:
return View("Index");
Run Code Online (Sandbox Code Playgroud)
这实际上不会调用控制器操作,它只是返回视图.要做你想做的事,你需要使用RedirectToAction:
return RedirectToAction("Index");
Run Code Online (Sandbox Code Playgroud)