2013-11-23 113 views
4

至於我知道,似乎微軟使用jQuery驗證屬性作爲表單輸入屬性的默認值。ASP.NET MVC 5和HTML 5根據W3C規範形成屬性

是否可以配置我的應用程序,所以如果我加入Required屬性和使用@Html.EditorFor(x => Model)形式將使用required屬性,而不是data-val-required渲染渲染我的形式?還是我不得不爲所有標準類型編寫我自己的EditorTemplates

+0

不一樣,但在SO問題下面,表單將使用Html屬性呈現「Required」。相當手動的方法,雖然http://stackoverflow.com/questions/6788231/mvc3-adding-css-class-based-on-model-attributes – Spock

+0

你可以關閉jQuery驗證你想要的元素,然後提供html5屬性thr。注意數據屬性是HTML5的一部分.. –

回答

9

如果你想在你的web.config禁用不顯眼的客戶端驗證以取代ASP.NET MVC使用的標準data-*驗證屬性,你應該開始:

<add key="ClientValidationEnabled" value="false" /> 

這將防止HTML輔助發光,從他們在你的輸入字段。

然後,您可以編寫標準類型的自定義編輯器模板。例如,對於字符串,這將是~/Views/Shared/editorTemplates/String.cshtml

@{ 
    var attributes = new Dictionary<string, object>(); 
    attributes["class"] = "text-box single-line"; 
    if (ViewData.ModelMetadata.IsRequired) 
    { 
     attributes["required"] = "required"; 
    } 
} 

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, attributes) 

而這幾乎是它。現在,每次你做一個Html.EditorFor(x => x.Foo)其中Foo是一個字符串屬性,將產生以下標記:

<input class="text-box single-line" id="Foo" name="Foo" required="required" type="text" value="" /> 

另外值得一提的是,如果你不希望禁用不顯眼的客戶端驗證,併爲您的整個的data-*屬性應用程序,但只適用於單個表單,你可以這樣做:

@using (Html.BeginForm()) 
{ 
    this.ViewContext.ClientValidationEnabled = false; 
    @Html.EditorFor(x => x.Foo) 
} 
+0

好吧,我明白了。謝謝! – Marcus

+0

@darindimitrov先生,您能否給我建議,可能是HTML5約束表單驗證的原因在我的mvc 5網站中不起作用。那麼,實際上它有點工作,但沒有警告信息顯示。我一直在尋找三天的解決方案:( –