C# - 自定义HTML帮助程序

时间:2014-02-09 22:29:17

标签: c# html asp.net-mvc-4 twitter-bootstrap html-helper

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

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

我还有一个Bootstrap Helper类,它使用以下代码创建文本框:

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());

取决于DataType是否设置为“密码”?

谢谢你们/女孩们!

1 个答案:

答案 0 :(得分:2)

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

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