Question

The standard output of @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 for the generation of the data-val-* attributes? They seem rather verbose and not needed just to be able to store and return data for the next POST.

Is it a good idea to disable these attributes? Are they usefull for some scenario's?

ps: Currently I 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);
    }
}

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

Was it helpful?

Solution

Just because the field is hidden, doesn't neccesarily mean you don't want the validation. You might be manipulating the hidden field via javascript, and want to keep the built in validation so you don't have to do your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top