Saturday, October 5, 2013

Strongly Typed Fluent MVC Extensions

In my earlier blog, I blogged on how to create a fluent MVCextension. In that blog I created a simple Label extension with two fluent methods that are chained together. In this blog I will convert that Label extension to a strongly typed extension which takes the model property and binds to it.

Below is the code from the previous blog. I will add the strongly typed extension to this code.

    public static class LabelExtensions
    {
        public static Label FluentLabel(this HtmlHelper helper)
        {
            return new Label();
        }
    }


    public class Label
    {
        private string target, text;

        public Label Target(string target)
        {
            this.target = target;
            return this;
        }

        public Label Text(string text)
        {
            this.text = text;
            return this;
        }

        public override string ToString()
        {
            return String.Format("<label for='{0}'>{1}</label>Fluent", target, text); ;
        }
    }

We can easily make this fluent label to a strongly typed fluent extension by adding an additional extension which takes model as the input parameter. Below is the code for this:

    public static Label FluentLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
                                        Expression<Func<TModel, TProperty>> expression)
    {
            //getting the name
        var name = ExpressionHelper.GetExpressionText(expression);
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        return new Label().Text(metadata.Model as string);
    }

With this addition extension we can make our Label as strong typed model Label. Here is how we can consume this Label

       @(Html.FluentLabelFor(m => m.Name).Target("firstName"))

No comments:

Post a Comment