加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP .NET MVC正确的UserControl架构

发布时间:2020-12-16 07:07:33 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试学习新的ASP .NET MVC框架,并希望了解使用UserControls的最佳实践. 我知道您可以将UserControl作为部分渲染,并从控制器传递数据.理想情况下,我认为没有代码隐藏文件是有道理的,因为这会产生破坏MVC规则的诱惑. 我将举一个例子,我不明白UserControl
我正在尝试学习新的ASP .NET MVC框架,并希望了解使用UserControls的最佳实践.

我知道您可以将UserControl作为部分渲染,并从控制器传递数据.理想情况下,我认为没有代码隐藏文件是有道理的,因为这会产生破坏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出现在每个页面上,那么解决此问题的一种方法是使用一个基本控制器,所有控制器都从该控制器派生并通过重写OnActionExecuting方法并将逻辑放在那里来为UserControl生成ViewData.如果您的UserControl不那么普遍,但仍然经常在整个站点中使用,您可以扩展ActionFilterAttribute并让您的过滤器生成所需的数据.此属性可用于装饰生成使用UserControl的视图的控制器或操作.

我在所有这些中假设UserControl的数据独立于被调用的动作.如果存在依赖关系,则最好将逻辑推入一个类(或类,可能使用策略),并在每个操作或控制器中显式生成数据(通过重写OnActionExecuting).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读