【问题标题】:ASP.net MVC v2 - Styling templatesASP.net MVC v2 - 样式模板
【发布时间】:2010-12-11 11:33:34
【问题描述】:

只是想知道是否有人对我们如何设置模板样式有任何想法...例如,如果我想更改文本框的 MaxLength,我该怎么做。

我想做的事情就像我可以在 WPF 中使用样式和模板做的事情...在 WPF 中,您可以将样式传递给模板,然后选择应用这些样式的位置...对于如果用户在控件(即模板)上设置宽度的实例,在控件代码中,我可以选择将该宽度应用于模板中我想要的任何元素或根本不应用......

因此我想知道是否有人知道类似的事情?

【问题讨论】:

    标签: asp.net-mvc templates styling


    【解决方案1】:

    我已经发布了一个类似问题的答案here

    如果您想要通用样式,您可以从支持您所需样式的基本 TemplateViewModel 类派生自定义模板的模型:

    public interface ITextSpecifier
    {
      int? Size { get; }
      bool AutoGrow { get; }
    }
    
    public class TemplateViewModel<T> where T: class
    {
      public IDictionary<string, string> Attributes { get; }
      public ITextSpecifier TextStyle { get; private set; }
      public IColorSpecifier ColorStyle { get; }
      public T TextStyle(int size, bool autogrow)
      {
         TextStyle = new TextSpecifier(size, autogrow);
         return this;
      }
    }
    
    public class TextBoxViewModel: TemplateViewModel<TextBoxViewModel>
    {
    }
    
    <%= Html.EditorFor(x => new TextBoxViewModel(Model.StringData).TextStyle(10, false)) %>
    

    在模板中:

    <!-- template page derived from typed control for TextBoxViewModel -->
    <input type='text' <%= Model.TextStyle.Size != null 
        ? "size='" + Model.TextStyle.Size + "'" : "" %> ... />
    

    这有点工作,这就是为什么我希望他们能在 MVC v2 版本中发明一些通用方法。

    【讨论】:

    • 我可以看到你在做什么......但正如你在另一篇文章中所说,我认为需要有更好的方法来处理问题......我认为 WPF 解决方案会起作用这里真的很好......
    • 这看起来可以解决我正在处理的问题。您希望的新事物是否已经出现在 v2 或 v3 中? T
    【解决方案2】:

    这里的解决方案是使用元数据!您可以在此处重用 StringLength 数据注释验证属性。创建一个新的元数据提供程序,从 StringLength 属性中读取最大长度并将其放入 AdditionalValues 字典。您的元数据提供者应该继承自 DataAnnotationsModelMetadataProvider。然后在您创建的模板中,在 DisplayTemplates 或 EditorTemplates 中,您可以访问字符串的最大长度。

    【讨论】:

      【解决方案3】:

      据我所知,最简单的方法是为文本框创建一个 HTML id,如下所示:

        @Html.EditorFor(model => model.Description, null, "Description", null)
      

      并在页面末尾,编写以下javascript

       <script type="text/javascript">
              $(function () { $("#Description").css("width","450"); });    
       </script>
      

      注意:- 即使我讨厌 MVC!!!

      【讨论】:

      • 你为什么讨厌设计模式?或者您是把 IE 称为“互联网”并将 ASP.NET MVC 框架称为“mvc”的人之一?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多