在我的ASP.NET MVC站点区域中执行全局视图数据的最佳方法?

前端之家收集整理的这篇文章主要介绍了在我的ASP.NET MVC站点区域中执行全局视图数据的最佳方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个控制器,我希望每个ActionResult返回相同的viewdata.在这种情况下,我知道我将始终需要基本的产品和员工信息.

现在我一直在做这样的事情:

  1. public ActionResult ProductBacklog(int id) {
  2. PopulateGlobalData(id);
  3. // do some other things
  4. return View(Strongviewmodel);
  5. }

其中PopulateGlobalData()定义为:

  1. public void PopulateGlobalData(int id) {
  2. ViewData["employeeName"] = employeeRepo.Find(Thread.CurrentPrincipal.Identity.Name).First().FullName;
  3. ViewData["productName"] = productRepo.Find(id).First().Name;
  4. }

这只是伪代码,所以原谅任何明显的错误,有没有更好的方法来做到这一点?我想让我的控制器继承一个几乎与你在这里看到的相同的类,但我没有看到任何巨大的优势.感觉我正在做的事情是错误的和不可维护的,最好的方法是什么?

解决方法

您可以编写一个自定义 action filter attribute,它将获取此数据并将其存储在使用此属性修饰的每个操作/控制器的视图模型中.
  1. public class GlobalDataInjectorAttribute : ActionFilterAttribute
  2. {
  3. public override void OnActionExecuted(ActionExecutedContext filterContext)
  4. {
  5. string id = filterContext.HttpContext.Request["id"];
  6. // TODO: use the id and fetch data
  7. filterContext.Controller.ViewData["employeeName"] = employeeName;
  8. filterContext.Controller.ViewData["productName"] = productName;
  9. base.OnActionExecuted(filterContext);
  10. }
  11. }

当然,使用基本视图模型和强类型视图会更加清晰:

  1. public class GlobalDataInjectorAttribute : ActionFilterAttribute
  2. {
  3. public override void OnActionExecuted(ActionExecutedContext filterContext)
  4. {
  5. string id = filterContext.HttpContext.Request["id"];
  6. // TODO: use the id and fetch data
  7. var model = filterContext.Controller.ViewData.Model as Baseviewmodel;
  8. if (model != null)
  9. {
  10. model.EmployeeName = employeeName;
  11. model.ProductName = productName;
  12. }
  13. base.OnActionExecuted(filterContext);
  14. }
  15. }

现在剩下的就是用这个属性装饰你的基本控制器:

  1. [GlobalDataInjector]
  2. public abstract class BaseController: Controller
  3. { }

还有另一个更有趣的解决方案,我个人更喜欢并涉及child actions.在这里,您定义了一个处理此信息检索的控制器:

  1. public class GlobalDataController: Index
  2. {
  3. private readonly IEmployeesRepository _employeesRepository;
  4. private readonly IProductsRepository _productsRepository;
  5. public GlobalDataController(
  6. IEmployeesRepository employeesRepository,IProductsRepository productsRepository
  7. )
  8. {
  9. // usual constructor DI stuff
  10. _employeesRepository = employeesRepository;
  11. _productsRepository = productsRepository;
  12. }
  13.  
  14. [ChildActionOnly]
  15. public ActionResult Index(int id)
  16. {
  17. var model = new Myviewmodel
  18. {
  19. EmployeeName = _employeesRepository.Find(Thread.CurrentPrincipal.Identity.Name).First().FullName,ProductName = _productsRepository.Find(id).First().Name;
  20. };
  21. return View(model);
  22. }
  23. }

现在剩下的就是include这个需要的地方(可能是全球的主页):

  1. <%= Html.Action("Index","GlobalData",new { id = Request["id"] }) %>

或者如果id是路由的一部分:

  1. <%= Html.Action("Index",new { id = ViewContext.RouteData.GetrequiredString("id") }) %>

猜你在找的asp.Net相关文章