C# - 自定义 HTML 帮助程序



我有以下代码在我的视图模型中设置变量。

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

我还有一个引导助手类,它使用以下代码创建文本框:

public static MvcHtmlString TextboxGroupFor<TModel, TProperty>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression,
    BootstrapInputSizes? width = BootstrapInputSizes.Defalut)
{
    var placeholder = string.Empty;
    if (html.ViewData.ModelMetadata.AdditionalValues.ContainsKey("placeholder"))
    {
        placeholder = html.ViewData.ModelMetadata.AdditionalValues["placeholder"] as string;
    }
    var sb = new StringBuilder();
    sb.AppendLine("<div class="form-group col-xs-12">");
    sb.AppendLine(html.LabelFor(expression, new { @class = "col-sm-2 control-label" }).ToHtmlString());
    sb.AppendLine("<div class=" col-sm-6">");
    sb.AppendLine(html.TextBoxFor(expression,
        new { @class = "form-control", @placeholder = placeholder }).ToHtmlString());
    sb.AppendLine("</div></div>");
    return new MvcHtmlString(sb.ToString());
}

我怎么能做以下行:

sb.AppendLine(html.TextBoxFor(expression,
                new { @class = "form-control", @placeholder = placeholder }).ToHtmlString());

肖:

sb.AppendLine(html.TextBoxFor(expression,
               new { @class = "form-control", @placeholder = placeholder , @type ="Password"}).ToHtmlString());

取决于数据类型是否设置为"密码"?

谢谢男生/女生!

您可以使用

FromLambdaExpression 方法获取 lambda 表达式指向的属性的ModelMetadata,然后检查 DataTypeName 属性的值很简单:

var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
if (metadata.DataTypeName == "Password")
{
    ... your model property was decorated with [DataType(DataType.Password)]
}

相关内容

  • 没有找到相关文章

最新更新