:version: 1.0.0-rc1 Working with Forms ==================== By `Rick Anderson`_, `Dave Paquette `_ and `Jerrie Pelser `__ This document demonstrates working with Forms and the HTML elements commonly used on a Form. The HTML `Form `__ element provides the primary mechanism web apps use to post back data to the server. Most of this document describes :doc:`Tag Helpers ` and how they can help you productively create robust HTML forms. We recommend you read :doc:`tag-helpers/intro` before you read this document. In many cases, :doc:`HTML Helpers ` provide an alternative approach to a specific Tag Helper, but it's important to recognize that Tag Helpers do not replace HTML Helpers and there is not a Tag Helper for each HTML Helper. When an HTML Helper alternative exists, it is mentioned. .. contents:: Sections: :local: :depth: 1 .. _my-asp-route-param-ref-label: The Form Tag Helper -------------------- The `Form `__ Tag Helper: - Generates the HTML `
`__ ``action`` attribute value for a MVC controller action or named route - Generates a hidden `Request Verification Token `__ to prevent cross-site request forgery (when used with the ``[ValidateAntiForgeryToken]`` attribute in the HTTP Post action method) - Provides the ``asp-route-`` attribute, where ```` is added to the route values. The ``routeValues`` parameters to ``Html.BeginForm`` and ``Html.BeginRouteForm`` provide similar functionality. - Has an HTML Helper alternative ``Html.BeginForm`` and ``Html.BeginRouteForm`` Sample: .. literalinclude:: working-with-forms/sample/final/Views/Demo/RegisterFormOnly.cshtml :language: HTML The Form Tag Helper above generates the following HTML: .. code-block:: HTML The MVC runtime generates the ``action`` attribute value from the Form Tag Helper attributes ``asp-controller`` and ``asp-action``. The Form Tag Helper also generates a hidden `Request Verification Token `__ to prevent cross-site request forgery (when used with the ``[ValidateAntiForgeryToken]`` attribute in the HTTP Post action method). Protecting a pure HTML Form from cross-site request forgery is very difficult, the Form Tag Helper provides this service for you. Using a named route ^^^^^^^^^^^^^^^^^^^ The ``asp-route`` Tag Helper attribute can also generate markup for the HTML ``action`` attribute. An app with a :doc:`route ` named ``register`` could use the following markup for the registration page: .. literalinclude:: working-with-forms/sample/final/Views/Demo/RegisterRoute.cshtml :language: HTML :emphasize-lines: 4 Many of the views in the *Views/Account* folder (generated when you create a new web app with *Individual User Accounts*) contain the `asp-route-returnurl `__ attribute: .. code-block:: none :emphasize-lines: 2
:Note: With the built in templates, ``returnUrl`` is only populated automatically when you try to access an authorized resource but are not authenticated or authorized. When you attempt an unauthorized access, the security middleware redirects you to the login page with the ``returnUrl`` set. The Input Tag Helper --------------------- The Input Tag Helper binds an HTML ` `__ element to a model expression in your razor view. Syntax: .. code-block:: HTML The Input Tag Helper: - Generates the ``id`` and ``name`` HTML attributes for the expression name specified in the ``asp-for`` attribute. ``asp-for="Property1.Property2"`` is equivalent to ``m => m.Property1.Property2``, that is the attribute value literally is part of an expression. The name of the expression is what's used for the ``asp-for`` attribute value. - Sets the HTML ``type`` attribute value based on the model type and `data annotation `__ attributes applied to the model property - Will not overwrite the HTML ``type`` attribute value when one is specified - Generates `HTML5 `__ validation attributes from `data annotation `__ attributes applied to model properties - Has an HTML Helper feature overlap with ``Html.TextBoxFor`` and ``Html.EditorFor``. See the **HTML Helper alternatives to Input Tag Helper** section for details. - Provides strong typing. If the name of the property changes and you don't update the Tag Helper you'll get an error similar to the following: .. code-block:: HTML An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately. Type expected 'RegisterViewModel' does not contain a definition for 'Email' and no extension method 'Email' accepting a first argument of type 'RegisterViewModel' could be found (are you missing a using directive or an assembly reference?) The ``Input`` Tag Helper sets the HTML ``type`` attribute based on the .NET type. The following table lists some common .NET types and generated HTML type (not every .NET type is listed). +---------------------+--------------------+ |.NET type | Input Type | +=====================+====================+ |Bool | type="checkbox" | +---------------------+--------------------+ |String | type="text" | +---------------------+--------------------+ |DateTime | type="datetime" | +---------------------+--------------------+ |Byte | type="number" | +---------------------+--------------------+ |Int | type="number" | +---------------------+--------------------+ |Single, Double | type="number" | +---------------------+--------------------+ The following table shows some common `data annotations `__ attributes that the input tag helper will map to specific input types (not every validation attribute is listed): +-------------------------------+--------------------+ |Attribute | Input Type | +===============================+====================+ |[EmailAddress] | type="email" | +-------------------------------+--------------------+ |[Url] | type="url" | +-------------------------------+--------------------+ |[HiddenInput] | type="hidden" | +-------------------------------+--------------------+ |[Phone] | type="tel" | +-------------------------------+--------------------+ |[DataType(DataType.Password)] | type="password" | +-------------------------------+--------------------+ |[DataType(DataType.Date)] | type="date" | +-------------------------------+--------------------+ |[DataType(DataType.Time)] | type="time" | +-------------------------------+--------------------+ Sample: .. literalinclude:: working-with-forms/sample/final/ViewModels/RegisterViewModel.cs :language: c# .. literalinclude:: working-with-forms/sample/final/Views/Demo/RegisterInput.cshtml :language: HTML The code above generates the following HTML: .. code-block:: HTML Email:
Password:
The data annotations applied to the ``Email`` and ``Password`` properties generate metadata on the model. The Input Tag Helper consumes the model metadata and produces `HTML5 `__ ``data-val-*`` attributes (see :doc:`/mvc/models/validation`). These attributes describe the validators to attach to the input fields. This provides unobtrusive HTML5 and `jQuery `__ validation. The unobtrusive attributes have the format ``data-val-rule="Error Message"``, where rule is the name of the validation rule (such as ``data-val-required``, ``data-val-email``, ``data-val-maxlength``, etc.) If an error message is provided in the attribute, it is displayed as the value for the ``data-val-rule`` attribute. There are also attributes of the form ``data-val-ruleName-argumentName="argumentValue"`` that provide additional details about the rule, for example, ``data-val-maxlength-max="1024"`` . HTML Helper alternatives to Input Tag Helper ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``Html.TextBox``, ``Html.TextBoxFor``, ``Html.Editor`` and ``Html.EditorFor`` have overlapping features with the Input Tag Helper. The Input Tag Helper will automatically set the ``type`` attribute; ``Html.TextBox`` and ``Html.TextBoxFor`` will not. ``Html.Editor`` and ``Html.EditorFor`` handle collections, complex objects and templates; the Input Tag Helper does not. The Input Tag Helper, ``Html.EditorFor`` and ``Html.TextBoxFor`` are strongly typed (they use lambda expressions); ``Html.TextBox`` and ``Html.Editor`` are not (they use expression names). Expression names ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The ``asp-for`` attribute value is a `ModelExpression `__ and the right hand side of a lambda expression. Therefore, ``asp-for="Property1"`` becomes ``m => m.Property1`` in the generated code which is why you don't need to prefix with ``Model``. You can use the "@" character to start an inline expression and move before the ``m.``: .. code-block:: HTML @{ var joe = "Joe"; } Generates the following: .. code-block:: HTML Navigating child properties ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can also navigate to child properties using the property path of the view model. Consider a more complex model class that contains a child ``Address`` property. .. literalinclude:: working-with-forms/sample/final/ViewModels/AddressViewModel.cs :language: c# :lines: 5-8 :dedent: 3 :emphasize-lines: 1- .. literalinclude:: working-with-forms/sample/final/ViewModels/RegisterAddressViewModel.cs :language: c# :lines: 5-14 :dedent: 3 :emphasize-lines: 8 In the view, we bind to ``Address.AddressLine1``: .. literalinclude:: working-with-forms/sample/final/Views/Demo/RegisterAddress.cshtml :language: HTML :emphasize-lines: 6 The following HTML is generated for ``Address.AddressLine1``: .. code-block:: HTML Expression names and Collections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sample, a model containing an array of ``Colors``: .. literalinclude:: working-with-forms/sample/final/ViewModels/Person.cs :language: c# :lines: 5-10 :dedent: 3 :emphasize-lines: 3 The action method: .. code-block:: c# public IActionResult Edit(int id, int colorIndex) { ViewData["Index"] = colorIndex; return View(GetPerson(id)); } The following Razor shows how you access a specific ``Color`` element: .. literalinclude:: working-with-forms/sample/final/Views/Demo/EditColor.cshtml :language: HTML The *Views/Shared/EditorTemplates/String.cshtml* template: .. literalinclude:: working-with-forms/sample/final/Views/Shared/EditorTemplates/String.cshtml :language: HTML Sample using ``List``: .. literalinclude:: working-with-forms/sample/final/ViewModels/ToDoItem.cs :language: c# :lines: 3-7 :dedent: 3 The following Razor shows how to iterate over a collection: .. literalinclude:: working-with-forms/sample/final/Views/Demo/Edit.cshtml :language: none The *Views/Shared/EditorTemplates/ToDoItem.cshtml* template: .. literalinclude:: working-with-forms/sample/final/Views/Shared/EditorTemplates/ToDoItem.cshtml :language: HTML :Note: Always use ``for`` (and *not* ``foreach``) to iterate over a list. Evaluating an indexer in a LINQ expression can be expensive and should be minimized. :Note: The commented sample code above shows how you would replace the lambda expression with the ``@`` operator to access each ``ToDoItem`` in the list. The Textarea Tag Helper ------------------------- The `Textarea Tag Helper `__ tag helper is similar to the Input Tag Helper. - Generates the ``id`` and ``name`` attributes, and the data validation attributes from the model for a ` The Label Tag Helper -------------------- - Generates the label caption and ``for`` attribute on a `