我在MVC5项目的几个方法中都有这个逻辑。它有效,但我一直在重复自己。
private PersonnelManagementEntities db = new PersonnelManagementEntities();
private ActiveDirectoryTools adt = new ActiveDirectoryTools();
private ManagerService ms = new ManagerService();
private UserService us = new UserService();
private CompanyService cs = new CompanyService();
public ActionResult CompanySummary(int id = 0)
{
//Repeating logic begins here
int setID = 0;
adt.GetUserInfo(User.Identity.Name);
//Fetch current users company
User currentUser = us.getUser(adt.adUserName);
//Determine if user is a global manager or not. If global display all companies
ViewBag.Company = cs.FetchCompanies(currentUser);
//You can only see the companies you're assigned to, in the AllRequests window. Unless manually overwritten in the URL
if (currentUser.GlobalUser == true && id > 0)
{
setID = id;
}
else
{
setID = (int)currentUser.CompanyID;
}
//End of repeating logic
var resultSet = db.UserTimeSummaryUpdated(setID);
return View(resultSet.ToList());
}
你们认为减少重复次数的最佳方式是什么?
您可以在此处看到我重用此代码的另一种方法:
public ActionResult AllRequests(int id = 0)
{
int setID = 0;
adt.GetUserInfo(User.Identity.Name);
User currentUser = us.getUser(adt.adUserName);
ViewBag.Company = cs.FetchCompanies(currentUser);
//You can only see the companies you're assigned to, in the AllRequests window. Unless manually overwritten in the URL
if (id > 0)
{
setID = id;
}
else
{
setID = (int)currentUser.CompanyID;
}
ViewBag.EmployeeList = db.Users
.Where(x => x.disabled == false)
.Where(x => x.CompanyID == setID)
.OrderBy(x => x.FullName)
.ToList();
IQueryable timeRequests = db.TimeRequests
.Include(t => t.ApproveDenyReason)
.Include(t => t.DayType)
.Include(t => t.User)
.Include(t => t.User1)
.Include(t => t.User2)
.OrderByDescending(t => t.sDateTime)
.Where(t => t.User.CompanyID == setID);
return View(timeRequests);
}
我正在考虑创建一个ActionFilter并以这种方式进行,但它似乎是一种黑客而不是正确的做事方式。 我还接受了用户登录时的想法,我创建了一个用户对象并通过会话持久化。 任何帮助表示赞赏
答案 0 :(得分:1)
一种选择是编写一个继承Controller的CustomController。我这样做是为了添加会员会话数据和可以写入我的LayoutView的消息输出系统。对于下面的示例,我假设FetchCompanies返回一个列表...
public class CustomController : Controller
{
private ActiveDirectoryTools _adt = new ActiveDirectoryTools();
private UserService _us = new UserService();
private CompanyService _cs = new CompanyService();
public List<Company> UserCompanies;
public ApplicationController()
: base()
{
_adt.GetUserInfo(User.Identity.Name);
User currentUser = _us.getUser(adt.adUserName);
UserCompanies = _cs.FetchCompanies(currentUser);
}
}
从此CustomController创建Controller继承时。然后在ActionResult中使用UserCompanies进行设置。
public AccountController:CustomController
{
public ActionResult Index()
{
ViewBag.Company = UserCompanies;
return View();
}
}