ASP.net MVC v2 - Styling templates

被刻印的时光 ゝ 提交于 2019-12-25 12:46:08

问题


Just wondering if anyone has any ideas on how we can style templates... Like if I want to change the MaxLength of a textbox how do I go about doing this.

What I would like to be able to do is something like what I can do in WPF with styles and templates... In WPF you can pass through styles to the templates and then choose where those styles are applied... For instances if the user sets the width on a control (which is the template), within the control code I can choose to apply that width to any element I want within template or to none at all...

Hence I was wondering if anyone knows of anything similar?


回答1:


I've posted an answer to a similar question here.

If you want generic styles, you can derive your custom templates's Models from the base TemplateViewModel class which will support your required styles:

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)) %>

In the template:

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

It's a bit of work, that's why I hope they'll invent some common method in MVC v2 release.




回答2:


The solution here is to use metadata! You can reuse the StringLength data annotation validation attribute here. Create a new metadata provider that reads the max length out of the StringLength attribute and puts it into the AdditionalValues dictionary. Your metadata provider should inherit from DataAnnotationsModelMetadataProvider. And then in the template that you create, in the DisplayTemplates or EditorTemplates, you can access the string's max length.




回答3:


The easiest way to do this as far as I know is to create a HTML id for the textbox like shown below:

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

And at the end of the page, write the following javascript

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

NB:- Even I hate MVC!!!



来源:https://stackoverflow.com/questions/1647609/asp-net-mvc-v2-styling-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!