views:

298

answers:

2

Hi guys

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?

Cheers Anthony

A: 

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.

queen3
I can see what you are getting at... but as you say in the other post I think there needs to be a better way of handling the problem... I think the WPF solution would work really well here...
vdhant
A: 

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.

Nunery