【发布时间】:2021-04-24 23:35:37
【问题描述】:
我在 ASP.NET MVC 5 中创建了登录和注册页面。注册页面上有一个角色选项,询问用户是管理员还是非管理员。
现在,如果尝试登录的用户是 admin,那么我必须显示数据库中存在的所有用户,但如果用户是 >non-admin 那么我必须在页面上显示“Hi!用户名”。
我在下面附上了我的 AccountController 的代码。
using MyFirstApp.DBModel;
using MyFirstApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyFirstApp.Controllers
{
public class AccountController : Controller
{
DEV_Training_DemoEntities objDEV_Training_DemoEntities = new DEV_Training_DemoEntities();
// GET: Account
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
UserModel objUserModel = new UserModel();
return View(objUserModel);
}
[HttpPost]
public ActionResult Register(UserModel objUserModel)
{
if(ModelState.IsValid)
{
if (!objDEV_Training_DemoEntities.AN_Users.Any(m => m.Username == objUserModel.Username))
{
AN_Users objUser = new AN_Users();
objUser.Name = objUserModel.Name;
objUser.DOB = objUserModel.DOB;
objUser.Username = objUserModel.Username;
objUser.Password = objUserModel.Password;
objUser.Gender = objUserModel.Gender;
objUser.Role = objUserModel.Role;
objDEV_Training_DemoEntities.AN_Users.Add(objUser);
objDEV_Training_DemoEntities.SaveChanges();
objUserModel.SucessMessage = "You are successfully registered!";
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Error", "Username already exists!");
return View();
}
}
return View();
}
public ActionResult Login()
{
LoginModel objLoginModel = new LoginModel();
return View(objLoginModel);
}
[HttpPost]
public ActionResult Login(LoginModel objLoginModel)
{
if(ModelState.IsValid)
{
if (objDEV_Training_DemoEntities.AN_Users.Where(m => m.Username == objLoginModel.Username && m.Password == objLoginModel.Password).FirstOrDefault() == null)
{
ModelState.AddModelError("Error", "Invalid Email-ID or Password!");
return View();
}
else
{
var curruser = objDEV_Training_DemoEntities.AN_Users.Where(m => m.Username == objLoginModel.Username && m.Password == objLoginModel.Password).FirstOrDefault();
if(curruser.Role)
Session["Username"] = objLoginModel.Username;
return RedirectToAction("Index", "Home");
}
}
return View();
}
public ActionResult Logout()
{
Session.Abandon();
return RedirectToAction("Index", "Home");
}
}
}
【问题讨论】:
-
有什么问题?你能显示错误吗?
-
没有错误,就是不知道怎么执行。
-
@Abhishek Negi,有更新吗?请检查我的答案是否适合您。
标签: c# sql-server asp.net-mvc visual-studio