asp.net-mvc - ASP .NET MVC正确的UserControl体系结构

标签 asp.net-mvc user-controls partial-views

我正在尝试学习新的ASP .NET MVC框架,并想了解使用UserControls的最佳实践。

我了解您可以将UserControl呈现为部分控件,并将数据从 Controller 传递给它们。理想情况下,我认为在文件后没有代码是有道理的,因为这会产生破坏MVC规则的诱惑。

我将给出一个示例,在该示例中我不了解UserControls如何适合该模式。

I have a UserControl that shows the latest tags (much like on StackOverflow). Unlike StackOverflow I want to display this UserControl on all of my pages. If I have a controller say QuestionController which is meant to handle actions from some question views e.g. view and detail, does this mean I have to fetch the data in the QuestionController and then pass it to the UserControl?

If I create another controller say SearchController then I would have to replicate the same functionality to get the latest tags to pass to a partial again. Doesn't this mean that the 2 different controllers are doing extra things that they weren't originally intended to do?

最佳答案

如果您的UserControl出现在每个页面上,则解决此问题的一种方法是使用基本 Controller ,您的所有 Controller 都将通过重写OnActionExecuting方法并将逻辑放在那里来从其派生并生成UserControl的ViewData。如果您的UserControl普及程度较低,但仍在整个站点中经常使用,则可以扩展ActionFilterAttribute并让您的过滤器生成所需的数据。此属性可用于装饰生成使用UserControl的 View 的 Controller 或操作。

在所有这些中,我假设UserControl的数据与所调用的 Action 无关。如果存在依赖关系,则最好将逻辑插入一个类(或多个类,也许使用Strategy),并在每个 Action 或 Controller 中明确显示数据的生成(通过重写OnActionExecuting)。

关于asp.net-mvc - ASP .NET MVC正确的UserControl体系结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/705033/

相关文章:

c# - 通过属性设置 Treeview HierarchicalDataTemplate

c# - 带有嵌入式 MonthCalendar 问题的 UserControl

c# - 服务端如何获取signalR客户端的连接ID?

c# - Name For 在编辑器模板中遍历集合时生成不正确的名称

WPF - 在 UserControl 中托管内容

c# - 将枚举传递给强类型部分 View

jquery - $(document).ready() 和部分 View 加载

jquery - MVC 动态部分 View 数据在 IE7 中消失

c# - Linq 选择表映射( Entity Framework )

c# - 当参数发生异常时重定向