Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Commit

Permalink
Add FormTagHelper.
Browse files Browse the repository at this point in the history
- Added the FormTagHelper.
- Utilized the IHtmlGenerator to share base functionality with the HTMLHelper counterparts.
- Added tests to validate FormTagHelper functionality.

#1246
  • Loading branch information
NTaylorMullen authored and dougbu committed Oct 16, 2014
1 parent 4ea40b4 commit 1a5f8e1
Show file tree
Hide file tree
Showing 4 changed files with 680 additions and 0 deletions.
132 changes: 132 additions & 0 deletions src/Microsoft.AspNet.Mvc.TagHelpers/FormTagHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Razor.TagHelpers;

namespace Microsoft.AspNet.Mvc.TagHelpers
{
/// <summary>
/// <see cref="ITagHelper"/> implementation targeting &lt;form&gt; elements.
/// </summary>
[ContentBehavior(ContentBehavior.Append)]
public class FormTagHelper : TagHelper
{
private const string RouteAttributePrefix = "route-";

[Activate]
private ViewContext ViewContext { get; set; }

[Activate]
private IHtmlGenerator Generator { get; set; }

/// <summary>
/// The name of the action method.
/// </summary>
/// <remarks>
/// If value contains a '/' this <see cref="ITagHelper"/> will do nothing.
/// </remarks>
public string Action { get; set; }

/// <summary>
/// The name of the controller.
/// </summary>
public string Controller { get; set; }

/// <summary>
/// The HTTP method for processing the form, either GET or POST.
/// </summary>
public string Method { get; set; }

/// <summary>
/// Whether the anti-forgery token should be generated. Defaults to <c>true</c> if <see cref="Action"/> is not
/// a URL, <c>false</c> otherwise.
/// </summary>
[HtmlAttributeName("anti-forgery")]
public bool? AntiForgery { get; set; }

/// <inheritdoc />
/// <remarks>Does nothing if <see cref="Action"/> contains a '/'.</remarks>
public override void Process(TagHelperContext context, TagHelperOutput output)
{
bool antiForgeryDefault = true;

var routePrefixedAttributes = output.FindPrefixedAttributes(RouteAttributePrefix);

// If Action contains a '/' it means the user is attempting to use the FormTagHelper as a normal form.
if (Action != null && Action.Contains('/'))
{
if (Controller != null || routePrefixedAttributes.Any())
{
// We don't know how to generate a form action since a Controller attribute was also provided.
throw new InvalidOperationException(
Resources.FormatFormTagHelper_CannotDetermineAction(
"<form>",
nameof(Action).ToLowerInvariant(),
nameof(Controller).ToLowerInvariant(),
RouteAttributePrefix));
}

// User is using the FormTagHelper like a normal <form> tag, anti-forgery default should be false to
// not force the anti-forgery token onto the user.
antiForgeryDefault = false;

// Restore Action, Method and Route HTML attributes if they were provided, user wants non-TagHelper <form>.
output.CopyHtmlAttribute(nameof(Action), context);

if (Method != null)
{
output.CopyHtmlAttribute(nameof(Method), context);
}
}
else
{
var routeValues = GetRouteValues(output, routePrefixedAttributes);
var tagBuilder = Generator.GenerateForm(ViewContext,
Action,
Controller,
routeValues,
Method,
htmlAttributes: null);

if (tagBuilder != null)
{
// We don't want to do a full merge because we want the TagHelper content to take precedence.
output.Merge(tagBuilder);
}
}

if (AntiForgery ?? antiForgeryDefault)
{
var antiForgeryTagBuilder = Generator.GenerateAntiForgery(ViewContext);
if (antiForgeryTagBuilder != null)
{
output.Content += antiForgeryTagBuilder.ToString(TagRenderMode.SelfClosing);
}
}
}

// TODO: We will not need this method once https://github.com/aspnet/Razor/issues/89 is completed.
private static Dictionary<string, object> GetRouteValues(
TagHelperOutput output, IEnumerable<KeyValuePair<string, string>> routePrefixedAttributes)
{
Dictionary<string, object> routeValues = null;
if (routePrefixedAttributes.Any())
{
// Prefixed values should be treated as bound attributes, remove them from the output.
output.RemoveRange(routePrefixedAttributes);

// Generator.GenerateForm does not accept a Dictionary<string, string> for route values.
routeValues = routePrefixedAttributes.ToDictionary(
attribute => attribute.Key.Substring(RouteAttributePrefix.Length),
attribute => (object)attribute.Value);
}

return routeValues;
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 123 additions & 0 deletions src/Microsoft.AspNet.Mvc.TagHelpers/Resources.resx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="FormTagHelper_CannotDetermineAction" xml:space="preserve">
<value>Cannot determine an {1} for {0}. A {0} with a URL-based {1} must not have attributes starting with {3} or a {2} attribute.</value>
</data>
</root>
Loading

0 comments on commit 1a5f8e1

Please sign in to comment.