asp.net mvc 实现登录的控制器,视图代码
时间: 2023-04-04 14:03:10 浏览: 101
以下是一个简单的 ASP.NET MVC 登录控制器和视图代码示例:
控制器代码:
```
public class AccountController : Controller
{
// GET: Account/Login
public ActionResult Login()
{
return View();
}
// POST: Account/Login
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// 验证用户输入的用户名和密码是否正确
if (model.Username == "admin" && model.Password == "password")
{
// 登录成功,将用户信息存储在 Session 中
Session["Username"] = model.Username;
return RedirectToAction("Index", "Home");
}
else
{
// 登录失败,添加错误信息到 ModelState 中
ModelState.AddModelError("", "用户名或密码不正确");
}
}
// 如果代码执行到这里,说明登录失败,返回登录视图并显示错误信息
return View(model);
}
// GET: Account/Logout
public ActionResult Logout()
{
// 清除 Session 中的用户信息
Session.Clear();
return RedirectToAction("Index", "Home");
}
}
```
视图代码:
```
@model LoginViewModel
@{
ViewBag.Title = "登录";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Username)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<button type="submit" class="btn btn-primary">登录</button>
}
```
注意:以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)