For example, there is a class:
Public class User
{
Public string Name {get; set ;}
}
On the strong type view page, the input element corresponding to the attribute Name is displayed, and you want to add a title attribute and the corresponding value,
□Ideas
→ Custom TooltipAttribute, which can be attached to the Name attribute.
→ Custom DataAnnotationsModelMetadataProvider: place the Tooltip attribute value of TooltipAttribute into ModelMetadata. The value type is the AdditionalValues attribute of the key-value pair.
→ Write an extension method of HtmlHelper <TModel> to obtain the AdditionalValues attribute value of ModelMetadata.
Call the custom feature TooltipAttribute to the property.
Using MvcApplication1.Extension;
Namespace MvcApplication1.Models
{
Public class User
{
[Tooltip ("Enter the user name")]
Public string Name {get; set ;}
}
}
Custom DataAnnotationsModelMetadataProvider: place the Tooltip attribute value of the custom feature TooltipAttribute into AdditionalValues of ModelMetadata.
Extended HtmlHelper <TModel>. First, obtain the ModelMetadata related to the model, from ModelMetadata. in AdditionalValues, the value of Tooltip is typed in the Name attribute of the User. The value is [Tooltip ("enter User Name")] corresponding to the input parameter title = "enter User Name ".
using System.Linq.Expressions;namespace System.Web.Mvc{ public static class TooltipExtension { public static MvcHtmlString TooltipFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel,TValue>> expression) { var modelMetadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); if (modelMetadata.AdditionalValues.ContainsKey("Tooltip")) { return new MvcHtmlString((string)modelMetadata.AdditionalValues["Tooltip"]); } return new MvcHtmlString(""); } }}
Register the custom DataAnnotationsModelMetadataProvider globally.
Protected void Application_Start ()
{
......
ModelMetadataProviders. Current = new CustomModelMetadataProvider ();
}
View:
@ Model MvcApplication1.Models. User
@ Html. TextBoxFor (model => model. Name, new {title = @ Html. TooltipFor (model => model. Name )})
References:
Creating your own modelmetadataprovider to handle custom attributes