asp.net-mvc - ASP.NET MVC中的ModelFactory解决 'RenderPartial'问题

标签 asp.net-mvc renderpartial

ASP.NET MVC中的“RenderPartial()”方法提供的功能级别很低。它没有提供,也没有尝试提供真正的“子 Controller ”模型*。

通过“RenderPartial()”呈现的控件数量越来越多。它们分为3个主要类别:

1) Controls that are direct descendants of a specific page that use that page's model

2) Controls that are direct descendants of a specific page that use that page's model with an additional key of some type. Think implementation of 'DataRepeater'.

3) Controls that represent unrelated functionality to the page they appear on. This could be anything from a banner rotator, to a feedback form, store locator, mailing list signup. The key point being it doesn't care what page it is put on.



由于ViewData模型的工作方式,每个请求仅存在一个模型对象-也就是说,页面模型中必须存在子控件所需的任何内容。

最终,MVC团队有望提出一个真正的“子 Controller ”模型,但在那之前,我只是将子控件还需要的任何内容添加到主页模型中。

在上述(3)的情况下,这意味着我的“ProductModel”模型可能必须包含“MailingListSignup”模型的字段。显然,这并不理想,但是我已经接受了当前框架的最佳折衷方案,而且也不太可能“关闭” future 子 Controller 模型的所有门。

Controller 应该负责获取模型的数据,因为模型实际上应该只是一个哑数据结构,不知道从何处获取数据。但是我不希望 Controller 必须在几个不同的地方创建模型。

我已经开始做的是创建一个工厂来创建模型。该工厂由 Controller 调用(模型不知道该工厂)。
public static class JoinMailingListModelFactory {

        public static JoinMailingListModel CreateJoinMailingListModel() {

            return new JoinMailingListModel()
            {
                MailingLists = MailingListCache.GetPartnerMailingLists();
            };
        }
    }   

所以我的实际问题是,其他遇到相同问题的人如何实际创建模型。将来与新的MVC功能兼容的最佳方法是什么?

  • 注意:RenderAction()存在一些问题,我将不在这里讨论-尤其是它仅存在于MVCContrib中,而不会出现在ASP.NET-MVC的RTM版本中。其他问题导致sufficent problems我选择不使用它。因此,让我们暂时假设只有RenderPartial()存在-或者至少那是我决定使用的。
  • 最佳答案

    我在这种情况下看到的一种方法是使用 Action 过滤器填充部分 View 的数据-即子类ActionFilterAttribute。在OnActionExecuting中,将数据添加到ViewData中。然后,您只需要用过滤器装饰使用该局部 View 的不同操作即可。

    关于asp.net-mvc - ASP.NET MVC中的ModelFactory解决 'RenderPartial'问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/641600/

    相关文章:

    c# - 在 ASP.NET MVC 中发布序列化的 ASP.NET 模型和具有单个 Jquery Ajax 调用的文件

    c# - 回发到 Controller 时,MVC SelectList 在模型中为空

    asp.net - 允许更广泛的输入范围后验证危险字符MVC模型字段的正确方法

    asp.net-mvc - 在 MVC3 中如何拦截文件请求以检查权限?

    javascript - 在 Ruby on Rails 中的 JavaScript 事件中重新呈现局部 View

    ruby-on-rails - 向 FormBuilder 添加一个方法,该方法调用一个渲染部分的辅助方法

    asp.net - 使用自定义 http 模块时,IIS 7 中默认页面的 AJAX 部分呈现问题