简体   繁体   中英

C# - Custom HTML Helper

I have the following code to set up a variable in my view model.

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

I also have a Bootstrap Helper class which creates text boxes using the following code:

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

How would I be able to make the following line:

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

Look like:

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

Depending on whether or not the DataType is set to "Password"?

Thanks guys/girls!

You could get the ModelMetadata of the property to which the lambda expression is pointing using the FromLambdaExpression method and then it is a simple matter of inspecting the value of the DataTypeName property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM