2011-08-05 55 views
6

@Html.HiddenFor(model => model.Id)標準輸出是爲什麼Html.HiddenFor生成數據val-屬性

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="0" /> 

是否有必要爲data-val-*屬性的產生?它們看起來很冗長,並且不需要只是爲了能夠存儲和返回下一次POST的數據。

禁用這些屬性是一個好主意嗎?它們對某些場景有用嗎?

PS:目前我有辦法通過使用這兩個類臨時設置ViewContext.UnobtrusiveJavaScriptEnabled = false

禁用它們:

public static class Extensions 
{ 
    public static NoUnobtrusiveJavaScript NoUnobtrusiveJavaScript(this HtmlHelper htmlHelper) 
    { 
     return new NoUnobtrusiveJavaScript(htmlHelper.ViewContext); 
    } 
} 

public class NoUnobtrusiveJavaScript: IDisposable 
{ 

    private bool _disposed; 
    private readonly bool _unobtrusiveJavaScript; 
    private readonly ViewContext _viewContext; 

    public NoUnobtrusiveJavaScript(ViewContext viewContext) 
    { 
     if (viewContext == null) { 
      throw new ArgumentNullException("viewContext"); 
     } 

     _viewContext = viewContext; 
     _unobtrusiveJavaScript = viewContext.UnobtrusiveJavaScriptEnabled; 
     _viewContext.UnobtrusiveJavaScriptEnabled = false; 
    } 

    public void Dispose() 
    { 
     Dispose(true /* disposing */); 
     GC.SuppressFinalize(this); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!_disposed) 
     { 
      _disposed = true; 
      // restore the original UnobtrusiveJavaScriptEnabled state 
      if (_viewContext != null) 
      { 
       _viewContext.UnobtrusiveJavaScriptEnabled = _unobtrusiveJavaScript; 
      } 
     } 
    } 

    public void EndForm() 
    { 
     Dispose(true); 
    } 
} 

*模式下從FormExtensions.cs的Html.BeginForm代碼和MvcForm.cs

+0

如果你想關閉驗證,看看這個答案:http://stackoverflow.com/questions/4700172/unrequired-property-keeps-getting-data-val-required-attribute/4845768#4845768 – frennky

回答

1

只是因爲該字段是隱藏的,並不意味着你不想驗證。您可能正在通過javascript操作隱藏字段,並希望保持內置驗證,因此您不必自己做。

相關問題