私が提示した質問には、少なくとも 2 つの個別の解決策があることがわかりました。
MVC モデルへのツールチップの追加
この場合、組み込みの HtmlHelper を拡張する拡張メソッドを作成しました。
public static MvcHtmlString TextBoxWithTooltipFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes = null)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object> { { TITLE_ATTRIBUTE_NAME, metaData.Description } };
}
else
{
if (!string.IsNullOrEmpty(metaData.Description) && !htmlAttributes.Keys.Contains(TITLE_ATTRIBUTE_NAME))
htmlAttributes.Add(TITLE_ATTRIBUTE_NAME, metaData.Description);
}
return helper.TextBoxFor(expression, htmlAttributes);
}
これはモデルがどのように見えるかです
[Display(ResourceType = typeof(Resources.Resources), Name = "FirstNameLabel", Description = "FirstNameTooltip")]
public string FirstName { get; set; }
これは、Razorでこれを使用する方法です
@Html.TextBoxWithTooltipFor(m => m.FirstName, new { type = "text", required = string.Empty })
透かしを追加する
Model属性をエレガントな方法で活用することができなかったので、 JQueryソリューションを選択しました。これは、同様のパターンの他のサンプルから変更したJQueryです。
$.fn.Watermark = function (text) {
return this.each(
function () {
//This ensures Diacritic characters are encoded correctly
text = $('<span>' + text + '</span>').text();
var input = $(this);
map[map.length] = { text: text, obj: input };
function clearMessage() {
if (input.val() == text)
input.val("");
input.removeClass("watermark");
}
function insertMessage() {
if (input.val().length == 0 || input.val() == text) {
input.val(text);
input.addClass("watermark");
} else
input.removeClass("watermark")
}
input.focus(clearMessage);
input.blur(insertMessage);
input.change(insertMessage);
insertMessage();
}
);
};
透かしのスタイルを設定するCSSは次のとおりです
fieldset input[type="tel"].watermark,
fieldset input[type="email"].watermark,
fieldset input[type="text"].watermark,
fieldset input[type="password"].watermark {
color : #9B9B9B;
font-size: 0.7em;
font-style: italic;
}
これは、Razorでこれを使用する方法です
$("#FirstName").Watermark("@Resources.FirstNameWatermark");
注: フォームを送信する前に透かしをクリアしてください。これは、上記で提供したJQueryのバリエーションで実行でき、次のように使用できます。
$('#Application').submit(function () {
$.Watermark.RemoveAll();
return true;
});