Why does Html.HiddenFor generate data-val attributes

The standard output @Html.HiddenFor(model => model.Id) is

 <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" /> 

Is there a need to generate data-val-* attributes? They seem pretty detailed and not needed to be able to store and return data for the next POST.

Can I disable these attributes? Are they useful for some scenarios?

ps: I currently have a way to disable them by temporarily setting ViewContext.UnobtrusiveJavaScriptEnabled = false

using these two classes:

 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); } } 

* the template following the Html.BeginForm code from FormExtensions.cs and MvcForm.cs

+6
source share
1 answer

Just because the field is hidden does not mean you do not want validation. You can manipulate the hidden field using javascript and want to keep the built-in validation so you don't have to do your own.

+1
source

Source: https://habr.com/ru/post/894374/


All Articles