HTML and CSS Reference
In-Depth Information
string placeHolder;
string value;
string valueAttribute;
ViewDataDictionary viewData = htmlHelper.ViewData;
ModelMetadata metaData = viewData.ModelMetadata;
// Build the HTML attributes
id = viewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
name = viewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
if (string.IsNullOrWhiteSpace(metaData.Watermark))
placeHolder = string.Empty;
else
placeHolder = "placeholder=\"" + metaData.Watermark + "\"";
value = viewData.TemplateInfo.FormattedModelValue.ToString();
if (string.IsNullOrWhiteSpace(value))
valueAttribute = string.Empty;
else
valueAttribute = "value=\"" + value + "\"";
// Determine the css class
string css = "text-box single-line";
ModelState state;
if (viewData.ModelState.TryGetValue(name, out state)
&& (state.Errors.Count > 0))
css += " " + HtmlHelper.ValidationInputCssClassName;
// Format the final HTML
string markup = string.Format(Culture,
"<input type=\"email\" id=\"{0}\" name=\"{1}\" {2} {3} " +
"class=\"{4}\"/>", id, name, placeHolder, valueAttribute, css);
return MvcHtmlString.Create(markup);
}
This method gathers the various HTML attributes such as
id
,
name
,
class
, and
placeholder
. This
information is extracted from the model or the model metadata. At the end of this method, the
markup
string is
built using the standard
string.Format()
method, which assembles the various attributes. This is then passed to
the static
MvcHtmlString.Create()
method to provide this as the
IHtmlString
interface that the MVC framework
requires.
The primary difference in this implementation of the
EmailAddress
template is that the placeholder attribute
is set using the model metadata. The previous implementation used a hard-coded placeholder, “Enter an e-mail
address”. Unfortunately, the property names are completely inconsistent. In the model, this is specified using the
Prompt
attribute (
Prompt
=
"Preferred e-mail address"
). In the
ModelMetadata
class, this value is provided as
the
Watermark
property. And, of course, this is included in the HTML document as a
placeholder
attribute.
Re-implementing the Custom Email Template
Now you'll replace the EmailAddress template with a much simpler one that uses the new helper extension that
you've just implemented.