HiddenInput DataAnnotation attribute in Asp.net MVC3 Razor

  1. The HiddenInput attribute lives in the System.Web.Mvc namespace and tells the run time to render an input element with a type of "hidden".
  2. Hidden inputs are a great way to keep information in a form so the browser will send the data back to the server, but the user will not be able to see or edit the data.
  3. The property that has HiddenInput defined on it will be rendered as input type hidden on form.
Example :


In the above screenshot we have a EmployeeId property in View model. We have applied HiddenInput Data Annotation attribute on this property. we have also set its DisplayValue property to true. The true value indicates that the value of the hidden field will be shown on UI with a label. 

Controller :


In the controller, in Register Action method we have created object of view model, assigned 5 to EmployeeId property and this object is passed as model to the View. So, when the view renders it shows the value 5 on UI.

View :

@model CustomValidation.Models.Register

@{
    ViewBag.Title = "Register";
    Layout = null;
}



<h2 align="center">Register</h2>
@using (Html.BeginForm("Welcome","Register",new {@id = "formClass"}))
{
    <fieldset style="width:400px;">
    <legend>Registration Form</legend>
    @Html.EditorForModel("Register")
    <br /><br />
    <input type="submit" value="Submit" />
    </fieldset>
}

We have used EditorForModel to render our form content i.e. View model properties.

UI :




The hidden field's value is displayed on UI in non editable form.

Rendered  HTML :


<div class="editor-label"><label for="EmployeeId">EmployeeId</label></div>
<div class="editor-field">5
<input data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="hidden" value="5" />
<span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>
</div>


Example 2 :

In this example, we are not going to show hidden field's value on UI.




In this example, we are setting DisplayValue property to false. So, the hidden field's value will not be shown on UI.

UI :


In this case empty form is rendered. Hidden field is rendered but not displayed on UI.

Rendered HTML :


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


Thus we can use HiddenInput DataAnnotation attribute on property to render property as hidden field. 

0 comments:

Post a Comment