2010-08-12 44 views
7

如何在MVC 2中設置文本框的MaxLength和Size? 在SO上有幾個關於這個問題的問題。作爲MVC的新手,我發現沒有任何一種解決方案看起來可行 - 可能是因爲我沒有做對。MVC 2 EditorFor MaxLength和Size

在任何情況下,我想知道是否有更好的解決方案,因爲之前的問題似乎是在MVC 2處於測試階段時被問到的。

回答

9

這很容易,你只要有多餘的htmlAtttributes

<%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", width = "15" }) %> 
<%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", style = "width:200px;" }) %> 
+0

令人驚歎!他們確實在Beta版後修復了它。即便如此,我發現只有第二條線在您的解決方案中起作用。此外,該解決方案只適用於TextBoxFor而不適用於EditorFor,儘管現在我沒有問題。 – arame3333 2010-08-12 10:00:21

+0

您可以像那樣傳遞任何html屬性,但請記住,它們必須對HTML助手生成的指定html元素有效 - 在這種情況下,它是輸入。 – 2010-08-12 10:03:31

+7

主題標題說EditorFor - 回答說TextBoxFor。僅供參考 - 除非使用System.ComponentModel.DataAnnotations「[StringLength(5,ErrorMessage =」必須是5個或更少的字符「)]」裝飾屬性,否則額外的HtmlAttributes不能與EditorFor一起使用,否則需要更改爲TextBoxFor,然後我們可以使用答案中提到的額外HtmlAttributes。 – 2012-02-06 21:12:35

0

上述解決方案的工作,但如果你有一個領域的多個實例,它會更容易將其設置在模型或視圖模型。修改實際模型時要小心,因爲它們在更新時會變得不穩定。

示例: 在模型或視圖模型中。

[DisplayName("Notes")] 
[MaxLength(500, ErrorMessage="Maximum length of notes field is 500 characters...")] 
[DataType(DataType.MultilineText)] 
public string Notes { get; set; } 

要驗證它提交,你需要在你的web.config中。

<add key="ClientValidationEnabled" value="true" /> 
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

確保你的地方引用驗證JS文件,最好在共享/ _layout或頁面本身...

<script src="~/Scripts/jquery.validate.min.js"></script> 
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

最後請確保您包括在CSHTML確認消息。

@Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control", rows = "5", @placeholder = "Notes", title = "Enter any notes..." } }) 
@Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" }) 

構建解決方案並進行測試。希望這有助於任何人尋找解決方案。