gpt4 book ai didi

asp.net - 在我的 ASP.NET MVC 站点的区域中执行全局 View 数据的最佳方法?

转载 作者:行者123 更新时间:2023-12-01 15:55:06 25 4
gpt4 key购买 nike

我有几个 Controller ,我希望每个 ActionResult 都返回相同的 View 数据。在这种情况下,我知道我将始终需要基本的产品和员工信息。

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

public ActionResult ProductBacklog(int id)  {
PopulateGlobalData(id);
// do some other things
return View(StrongViewModel);
}

其中 PopulateGlobalData() 定义为:
    public void PopulateGlobalData(int id) {
ViewData["employeeName"] = employeeRepo.Find(Thread.CurrentPrincipal.Identity.Name).First().FullName;
ViewData["productName"] = productRepo.Find(id).First().Name;
}

这只是伪代码,所以请原谅任何明显的错误,有没有更好的方法来做到这一点?我曾想过让我的 Controller 继承一个类,它的功能与您在此处看到的几乎相同,但我没有看到任何很大的优势。感觉我正在做的事情是错误且不可维护的,解决这个问题的最佳方法是什么?

最佳答案

你可以写一个自定义 action filter attribute它将获取此数据并将其存储在每个使用此属性修饰的 Action / Controller 上的 View 模型中。

public class GlobalDataInjectorAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string id = filterContext.HttpContext.Request["id"];
// TODO: use the id and fetch data
filterContext.Controller.ViewData["employeeName"] = employeeName;
filterContext.Controller.ViewData["productName"] = productName;
base.OnActionExecuted(filterContext);
}
}

当然,使用基本 View 模型和强类型 View 会更简洁:
public class GlobalDataInjectorAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string id = filterContext.HttpContext.Request["id"];
// TODO: use the id and fetch data
var model = filterContext.Controller.ViewData.Model as BaseViewModel;
if (model != null)
{
model.EmployeeName = employeeName;
model.ProductName = productName;
}
base.OnActionExecuted(filterContext);
}
}

现在剩下的就是用这个属性装饰你的基本 Controller :
[GlobalDataInjector]
public abstract class BaseController: Controller
{ }

我个人更喜欢另一个更有趣的解决方案,它涉及 child actions .在这里,您定义了一个处理此信息检索的 Controller :
public class GlobalDataController: Index
{
private readonly IEmployeesRepository _employeesRepository;
private readonly IProductsRepository _productsRepository;
public GlobalDataController(
IEmployeesRepository employeesRepository,
IProductsRepository productsRepository
)
{
// usual constructor DI stuff
_employeesRepository = employeesRepository;
_productsRepository = productsRepository;
}

[ChildActionOnly]
public ActionResult Index(int id)
{
var model = new MyViewModel
{
EmployeeName = _employeesRepository.Find(Thread.CurrentPrincipal.Identity.Name).First().FullName,
ProductName = _productsRepository.Find(id).First().Name;
};
return View(model);
}
}

现在剩下的就是 include这在任何需要的地方(如果是全局性的,可能是母版页):
<%= Html.Action("Index", "GlobalData", new { id = Request["id"] }) %>

或者如果 id 是路线的一部分:
<%= Html.Action("Index", "GlobalData", 
new { id = ViewContext.RouteData.GetRequiredString("id") }) %>

关于asp.net - 在我的 ASP.NET MVC 站点的区域中执行全局 View 数据的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4198184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com