samedi 18 juillet 2015

C# Pass Class Property Name as parameter

In my razor view I am using an HTML Helper Extension method in order to use the Display Name attribute of my Model Property to display a placeholder value in a textbox. See example below.

My Helper Extension Method:

    public static MvcHtmlString TextBoxPlaceHolderFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

        if (!String.IsNullOrEmpty(labelText))
        {
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary<string, object>();
            }
            htmlAttributes.Add("placeholder", labelText);
        }
        return html.TextBoxFor(expression, htmlAttributes);
    }

My Model Property:

    [Display(Name = "First Name", Description = "Enter Display Name")]
    public string FirstName { get; set; }

Current Outcome: http://ift.tt/1Mh4JHd

Display Name of property displays inside the field as a placeholder.

However, sometimes I might want to use another property on the model for the placeholder text (like the Description property in the model above). How can I make it so a Model data annotation property can be passed in the razor view and the the placeholder uses the value of that property instead?

Example code of what I want is below.

The razor view with meta-data property passed:

@Html.TextBoxPlaceHolderFor(model => model.FirstName, new { @class = "form-control" }, MODELMETADATAPROPERTY HERE)

The HTML Helper Extension (what I imagine the code would do, probably need to use reflection or something?)

 public static MvcHtmlString TextBoxPlaceHolderFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes, MODELMETADATAPROPERTY HERE)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.MODELMETADATAPROPERTY HERE;

        if (!String.IsNullOrEmpty(labelText))
        {
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary<string, object>();
            }
            htmlAttributes.Add("placeholder", labelText);
        }
        return html.TextBoxFor(expression, htmlAttributes);
    }





Aucun commentaire:

Enregistrer un commentaire