在视图中优雅地显示由 ID 映射的数据对象
我有很多支持案例
和用户
。每个案例
都分配给一个具有唯一ID的用户
。我的数据模型使用 AssignedUser
用户 ID 引用来表示这一点。这很容易存储和检索,但不方便展示。
当我想要显示案例
列表时,用户属性应格式化为用户的用户名而不是其 ID,但此信息在案例内不可用。在案例存储库中检索用户名很困难,因为它是由单独的用户存储库提供的。
目前,我正在通过为案例的 AssignedUser
属性创建一个 DisplayFor(...)
模板,并在 OnActionExecuting 的 HttpContext 中构建用户字典来实现此目的,即然后由模板引用并转换为用户名。这工作得相当好,但是按照这种方法,我在每次请求时都使用许多并不总是必需的字典(分支、产品等)填充 HttpContext。
本能地,我应该在视图模型中传递用户数据,但这意味着正确检索它。 ASP.NET-MVC 中的最佳实践是什么,而不执行不必要的查询并使用无用的数据填充 HttpContext?
I have a bunch of support Cases
and Users
. Each Case
is assigned to a User
with a unique ID. My data model represents this with an AssignedUser
user ID reference. This is easy to store and retrieve, but not convenient to display.
When I want to display a list of Cases
, the user property should be formatted as the user's username and not their ID, but this information is not available inside the case. It is difficult to retrieve usernames inside the case repository, since it is provided by a separate user repository.
At the moment, I am doing it by creating a DisplayFor(...)
template for a case's AssignedUser
property and building a dictionary of users in the HttpContext at OnActionExecuting which is then referenced by the template and translated to a username. This works fairly well, but following this approach, I am populating the HttpContext at every request with a number of dictionaries (Branches, Products, etc.) that are not always necessary.
Instinctively, I should pass the user data in the view model, but that means retrieving it properly. What is the best-practice in ASP.NET-MVC without doing unnecessary queries and populating the HttpContext with useless data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终使用 AutoMapper 填充视图模型以进行显示,并将用户 ID 映射到用户名等。
I ended up using AutoMapper to populate view models for display and map user IDs to user names, et cetera.