Whilst playing with MVC 2, I came upon the need to display an element that I could later replace as the result of an AJAX callback. Starting with the DisplayFor<> HtmlHelper extension, I found that it simply outputs the given value as a string, with no way to later replace it. I could create a custom display template, but I wanted more fine-grained control.
So, I decided that needed some way to create a display element wrapped in a <span> tag. With a <span> tag and an id, I would be able to display the model-bound data, but later replace it as the result of a AJAX callback.
This is what I came up with:
1: /// <summary>
2: /// Creates a placeholder element displaying the value given by <paramref name="display"/>.
3: /// </summary>
4: /// <typeparam name="TModel">The type of the model.</typeparam>
5: /// <typeparam name="TValue">The type of the value.</typeparam>
6: /// <param name="html">The HtmlHelper being extended.</param>
7: /// <param name="display">The property from the model to display.</param>
8: /// <returns>An <see cref="MvcHtmlString"/> containing the display value wrapped in a <span> tag</returns>
9: public static MvcHtmlString PlaceholderFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> display ) { 10:
11: return PlaceholderFor( html, display, null );
12: }
13:
14: /// <summary>
15: /// Creates a placeholder element displaying the value given by <paramref name="display"/>.
16: /// </summary>
17: /// <typeparam name="TModel">The type of the model.</typeparam>
18: /// <typeparam name="TValue">The type of the value.</typeparam>
19: /// <param name="html">The HtmlHelper being extended.</param>
20: /// <param name="display">The property from the model to display.</param>
21: /// <param name="htmlAttributes">The HTML attributes.</param>
22: /// <returns>An <see cref="MvcHtmlString"/> containing the display value wrapped in a <span> tag</returns>
23: public static MvcHtmlString PlaceholderFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> display, IDictionary<string, object> htmlAttributes ) { 24:
25: ModelMetadata metaData = ModelMetadata.FromLambdaExpression( display, html.ViewData );
26: TagBuilder tag = new TagBuilder( "span" );
27: tag.GenerateId( metaData.PropertyName );
28: if( htmlAttributes != null ) { 29: tag.MergeAttributes( htmlAttributes );
30: }
31: tag.SetInnerText( Convert.ToString( metaData.Model, CultureInfo.CurrentCulture ) );
32: return MvcHtmlString.Create( tag.ToString( TagRenderMode.Normal ) );
33: }