Html.EditorFor and multiline textboxes in mvc4 and EF

asp.net-mvc, entity-framework, razor

Solution

Think i have part of my answer. By reading a lot more about TextTemplatesTransformations i have modified my Model1.tt to include:

System.ComponentModel.DataAnnotations;

i have also modified the WriteProperty method to accept an EdmPropertyType. The code now generates multiline annotations for all strings which came from a specified length > 60 or max defined strings. It also generates a maxlength annotation which should hopefully help prevent overflow. If using you will need to modify both the existing WriteProperty overloads as below.

void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty)
{
    WriteProperty(Accessibility.ForProperty(edmProperty),
                  code.Escape(edmProperty.TypeUsage),
                  code.Escape(edmProperty),
                  code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
                  code.SpaceAfter(Accessibility.ForSetter(edmProperty)),edmProperty);
}



void WriteProperty(string accessibility, string type, string name, string getterAccessibility, string setterAccessibility,EdmProperty edmProperty = null)
{
    if (type =="string")    
    {
        int maxLength = 0;//66
        bool bres = (edmProperty != null
            && Int32.TryParse(edmProperty.TypeUsage.Facets["MaxLength"].Value.ToString(), out maxLength));
        if (maxLength > 60) // want to display as a TextArea in html 
        {
#> 
    [DataType(DataType.MultilineText)]
    [MaxLength(<#=maxLength#>)]
<#+
        }
        else
        if (maxLength < 61 && maxLength > 0) 
        {
#> 
    [MaxLength(<#=maxLength#>)]
<#+
        }
        else
        if(maxLength <=0) //varchar(max)
        {
#> 
    [DataType(DataType.MultilineText)]
<#+
        }

    }
#>
    <#=accessibility#> <#=type#> <#=name#> { <#=getterAccessibility#>get; <#=setterAccessibility#>set; }
<#+
}

Ensure that the <#+ lines and the #> lines start at the begining of the line as i think this is a requirement of the TT syntax.

Tim

Problem

what is the criteria for `@HTMLEditorFor` autodetecting that the model's datatype would be more suitably displayed in a multiline textbox? Using MVC4,razor and EF4.3 DatabaseFirst. I am using the controller wizards scaffolded pages for the CRUD operations. The Edit.cshtml and Create.cshtml both are using ``` @Html.EditorFor(model => model.message) ``` To display the textbox. If I edit the scaffolded Myemail.cs class I can add a DataAnnotation like ``` [DataType(DataType.MultilineText)] public string message { get; set; } ``` I now get a `<TextArea>` generated (albeit a impractical size for starting using (one line and 178px). Should this not be automatic when the tt templates generate the models? or do i need to somehow modify the tt templates to assume a `<TextArea>` if the field is a `varchar` etc with a size greater than say 100? Cheers Tim

Original source