2011-08-29 57 views
8

我知道關於Razor視圖文件,我們可以這樣做: @ Html.TextBox(「username」,null,new {maxlength = 20 ,autocomplete =「off」})ASP.NET MVC 3 - 數據Annoation和文本框渲染的最大長度/大小

但是,我希望爲MVC創建一個模型,該模型可以用來創建一個明確定義文本框大小和最大長度的窗體。我嘗試在模型屬性的頂部使用[StringLength(n)],但似乎只做了驗證,而不是設置文本框的大小。

有沒有辦法,我們可以定義文本字段的長度作爲模型屬性頂部的數據註釋?因此,最終,我們可以通過使用剃刀映射到模型來創建整個表單,而不是明確地逐個拾取模型屬性以設置文本框的大小。

回答

14

下面是一個使用StringLengthAttribute自定義幫助的輪廓。

public class MyModel 
{ 
    [StringLength(50)] 
    public string Name{get; set;} 
} 

public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, 
     Expression<Func<TModel, TProperty>> expression) 
{ 

    var attributes = new Dictionary<string, Object>(); 
    var memberAccessExpression = (MemberExpression)expression.Body; 
    var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
     typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true); 

    if (stringLengthAttribs.Length > 0) 
    { 
     var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength; 

     if (length > 0) 
     { 
      attributes.Add("size", length); 
      attributes.Add("maxlength", length); 
     } 
    } 

    return helper.TextBoxFor(expression, attributes); 
} 
+0

這看起來不錯!在Html.EditorForModel()中可以使用與上面提到的類似的東西嗎? 謝謝你的幫助。 – frostshoxx

+0

@frostshoxx您可以使用[UIHintAttribute](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.uihintattribute.aspx)併爲每種數據類型製作自定義模板。我還沒有嘗試過。 – Eranga

3

這不行嗎?

public class ViewModel 
{ 
    [StringLength(20)] 
    public string UserName {get;set;} 
} 

在查看:

@Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"}) 

或:

@Html.EditorFor(x => x.UserName) 
+2

您提到的語法是正確的,但我希望只需調用@ Html.EditorForModel()並讓它呈現模型中的所有字段,而不是分別明確地呈現每個字段。除此之外,我還希望能夠將文本字段的大小定義爲數據註釋標記的一部分。請注意有[StringLength(20)]似乎沒有將文本字段的大小設置爲20.我希望這個澄清更多一點..謝謝! – frostshoxx

+0

@frostshoxx指定模型中的文本字段大小等表示邏輯違反了MVC的核心原則。除非你的意思是maxlength .. – redwards510

2

我發現我更喜歡我的觀點只是調用Html.EditorFor(...)。這意味着編輯器和顯示模板決定了我的視圖中控件的命運,這樣我的視圖代碼就被清理了很多 - 它只是對編輯器有html和通用請求。

以下鏈接給在得到這個工作的工作樣本的編輯模板 https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/

我用我的String.cshtml編輯模板類似(進去共享/ EditorTemplates) 。

@model object 
@using System.ComponentModel.DataAnnotations 
@{ 
    ModelMetadata meta = ViewData.ModelMetadata; 
    Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType; 
} 
@if(typeof(string).IsAssignableFrom(tModel)) { 

    var htmlOptions = new System.Collections.Generic.Dictionary<string, object>(); 

    var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault(); 
    if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null) 
    { 
     int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"]; 

     htmlOptions.Add("maxlength", maxLength); 

     if (maxLength < 20) 
     { 
      htmlOptions.Add("size", maxLength); 
     } 
    } 

    htmlOptions.Add("class", "regular-field"); 

    <text> 
     @Html.TextBoxFor(m => m, htmlOptions) 
    </text> 
} 
else if(typeof(Enum).IsAssignableFrom(tModel)) { 
    //Show a Drop down for an enum using: 
    //Enum.GetValues(tModel) 
    //This is beyond this article 
} 
//Do other things for other types... 

然後我模式被註釋,如:

[Display(Name = "Some Field", Description = "Description of Some Field")] 
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")] 
public string someField{ get; set; } 

而且我查看簡單地調用:

<div class="editor-label"> 
    @Html.LabelWithTooltipFor(model => model.something.someField) 
</div> 
<div class="editor-field"> 
    @Html.EditorFor(model => model.something.someField) 
    @Html.ValidationMessageFor(model => model.something.someField) 
</div> 

您也可能會注意到,我的String.cshtml編輯模板也自動神奇地處理Enum的,但是現在已經開始脫離當前的話題,所以我沒有那個c賦,我就在這裏說,該字符串編輯器模板可以拉額外的重量,並有可能谷歌已經對https://www.google.com/search?q=string+editor+template+enum

標籤用工具提示成才的是一個自定義HTML幫助,只是下降的描述到標籤的標題,有關每個標籤的鼠標懸停的更多信息。

如果您想在編輯器模板中執行此操作,我會推薦此方法。

相關問題