【问题标题】:Html.EditorFor and multiline textboxes in mvc4 and EFmvc4 和 EF 中的 Html.EditorFor 和多行文本框
【发布时间】:2012-04-28 09:38:46
【问题描述】:

@HTMLEditorFor 自动检测模型的数据类型是否更适合显示在多行文本框中的标准是什么?使用 MVC4、razor 和 EF4.3 DatabaseFirst。我正在使用控制器向导搭建页面进行 CRUD 操作。 Edit.cshtml 和 Create.cshtml 都在使用

@Html.EditorFor(model => model.message)

显示文本框。如果我编辑脚手架 Myemail.cs 类,我可以添加一个 DataAnnotation 像

 [DataType(DataType.MultilineText)]
 public string message { get; set; }

我现在生成了一个<TextArea>(尽管开始使用的大小不切实际(一行和 178 像素)。当 tt 模板生成模型时这不是自动的吗?还是我需要以某种方式修改 tt 模板以如果字段是 varchar 等大小大于 100 的字段,则假设为 <TextArea>

干杯 蒂姆

【问题讨论】:

    标签: asp.net-mvc entity-framework razor


    【解决方案1】:

    我想我有部分答案。通过阅读更多关于 TextTemplatesTransformations 我修改了我的 Model1.tt 以包括:

    System.ComponentModel.DataAnnotations;
    

    我还修改了 WriteProperty 方法以接受 EdmPropertyType。该代码现在为来自指定长度 > 60 或最大定义字符串的所有字符串生成多行注释。它还生成一个 maxlength 注释,希望有助于防止溢出。如果使用,您将需要修改现有的两个 WriteProperty 重载,如下所示。

    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; }
    <#+
    }
    

    确保 行从行首开始,因为我认为这是 TT 语法的要求。

    提姆

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-27
      • 2012-10-20
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多