[英]mvc helper for rendering custom textbox
在剃刀視圖內,我正在使用html helper
@Html.TextBoxFor(model => model.YearsInService, new { @class = "col-lg-1" })
呈現以下html
<input id="YearsInService" class="col-lg-1" type="text" value="" name="YearsInService"
data-val-required="The YearsInService field is required."
data-val-number="The field YearsInService must be a number."
data-val="true" disabled="disabled">
因為我想用這樣的工具提示消息實現驗證, 所以我需要像這樣呈現解決方案輸入元素
<input
data-msg-number="The field YearsInService must be a number."
data-rule-number="true"
data-rule-required="true"
id="YearsInService" name="YearsInService" type="text" value="" />
問題是:如何構建自定義mvc幫助程序以在razor視圖中呈現第二個html代碼?
您可以創建HtmlHelper擴展方法來輸出html。
public static MvcHtmlString ToolTipTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
IDictionary<string, object> attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
attributes.Add("data-msg-number", "The field YearsInService must be a number.");
attributes.Add("data-rule-number", true);
... other 'fixed' attributes as required
return InputExtensions.TextBoxFor(helper, expression, attributes);
}
然后在視圖中
@ToolTipTextBoxFor(m => m.YearsInService, new { @class = "col-lg-1" })
當然,您可以創建其他重載來匹配TextBoxFor()
方法重載。
編輯
從您的評論中,您還希望基於屬性驗證屬性生成data-rule-
屬性。 為此,您可以獲取ModelMetatdata
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
然后檢查其屬性
例如
if (metaData.IsRequired)
{
attributes.Add("data-rule-required", true);
}
如果我正確理解了您想要的內容,那么我確定您需要編輯器模板
您可以使用TextBoxFor重載之一添加自定義html屬性:
@Html.TextBoxFor(x => x.YearsInService, new { data_msg_number = "The field YearsInService must be a number.", data_rule_number="true" })
如果可以使用EditorFor
而不是TextBoxFor
則建議創建編輯器模板。 有一篇不錯的文章描述了基礎知識 。
如果您想創建一個新的Html.MySuperTextBoxFor
擴展方法,請查看this 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.