前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Why All The Lambdas?

Why All The Lambdas?

作者头像
阿新
发布2018-04-12 15:07:08
7000
发布2018-04-12 15:07:08
举报
文章被收录于专栏:c#开发者c#开发者

Why All The Lambdas?

Tuesday, November 27, 2012

"Why All The Lambdas?" is a question that comes up with ASP.NET MVC.

代码语言:javascript
复制
@Html.TextBoxFor(model => model.Rating)

Instead of lambdas, why don't we just pass a property value directly?

代码语言:javascript
复制
@Html.TextBoxFor(Model.Rating)

Aren't we simply trying to give a text input the value of the Rating property?

image
image

There is more going on here than meets the eye, so let's …

Start From The Top

If all we need is a text box with a value set to the Rating property, then all we need to do is write the following:

代码语言:javascript
复制
<input type="text" value="@Model.Rating" />

But, the input is missing an important attribute, the name attribute, which allows the browser to associate the value of the input with a name when it sends information back to the server for processing. In ASP.NET MVC we typically want the name of an input to match the name of a property or action parameter so model binding will work (we want the name Rating, in this case). The name is easy enough to add, but we need to remember to keep the name in synch if the property name ever changes.

代码语言:javascript
复制
<input type="text" value="@Model.Rating" name="Rating"/>

Creating the input manually isn't difficult, but there are still some open issues:

- If Model is null, the code will fail with an exception.

- We aren't providing any client side validation support.

- We have no ability to display an alternate value (like an erroneous value a user entered on a previous form submission – we want to redisplay the value, show an error message, and allow the user to fix simple typographical errors).

To address these scenarios we'd need to write some more code and use if statements each time we displayed a text input. Since we want to keep our views simple,we'll package up the code inside an HTML helper.

Without Lambdas

Custom HTML helpers are easy to create.  Let's start with a naïve helper to create a text input.

代码语言:javascript
复制
// this code demonstrates a point, don't use it
public static IHtmlString MyTextBox<T>(
    this HtmlHelper<T> helper, object value, string name)
{
         var builder = new TagBuilder("input");
    builder.MergeAttribute("type", "text");
    builder.MergeAttribute("name", name);
    builder.MergeAttribute("value", value.ToString());
    
    return  new HtmlString(
        builder.ToString(TagRenderMode.SelfClosing)
    );
}

The way you'd call the helper is to give it a value and a name:

代码语言:javascript
复制
@Html.MyTextBox(Model.Rating, "Rating")

There isn't much going on inside the helper, and the helper doesn't address any of the scenarios we thought about earlier. We'll still get an exception in the view if Model is null, so instead of forcing the view to give the helper a value (using Model.Rating), we'll instead have the view pass the name of the model property to use.

代码语言:javascript
复制
@Html.MyTextBox("Rating")

Now the helper itself can check for null models, so we don't need branching logic in the view.

代码语言:javascript
复制
// this code demonstrates a point, don't use it for real work
public static IHtmlString MyTextBox<T>(
    this HtmlHelper<T> helper, string propertyName)
{
    var builder = new TagBuilder("input");
    builder.MergeAttribute("type", "text");
    builder.MergeAttribute("name", propertyName);
 
    var model = helper.ViewData.Model;
    var value = "";

    if(model != null)
    {                
        var modelType = typeof(T);
        var propertyInfo = modelType.GetProperty(propertyName);
        var propertyValue = propertyInfo.GetValue(model);
        value = propertyValue.ToString();
    }
    
    builder.MergeAttribute("value", value);
 
    return new HtmlString(
        builder.ToString(TagRenderMode.SelfClosing)
    );
} 

The above helper is not only using the propertyName parameter to set the name of the input, but it also uses propertyName to dig a value out of the model using reflection. We can build robust and useful HTML helpers just by passing property names as strings (in fact many of the built-in helpers, like TextBox, accept string parameters to specify the property name). Giving the helper a piece of data (the property name) instead of giving the helper a raw value grants the helper more flexibility.

The problem is the string literal "Rating". Many people prefer strong typing, and this is where lambda expressions can help.

With Lambdas

Here is a new version of the helper using a lambda expression.

代码语言:javascript
复制
// this code demonstrates a point, don't use it for real work
public static IHtmlString MyTextBox<T>(
    this HtmlHelper<T> helper, 
    Func<T, object> propertyGetter,
    string propertyName)
{
    var builder = new TagBuilder("input");
    builder.MergeAttribute("type", "text");
    builder.MergeAttribute("name", propertyName);

    var value = "";
    var model = helper.ViewData.Model;
    
    if(model != null)
    {
        value = propertyGetter(model).ToString();
    }

    builder.MergeAttribute("value", value);

    return new HtmlString(
        builder.ToString(TagRenderMode.SelfClosing)
    );
}

Notice the reflection code is gone, because we can use the lambda expression to retrieve the property value at the appropriate time.  But look at how we use the helper in a view, and we'll see it is a step backwards.

代码语言:javascript
复制
@Html.MyTextBox(m => m.Rating, "Rating")

Yes, we have some strong typing, but we have to specify the property name as a string. Although the helper can use the lambda expression to retrieve a property value, the lambda doesn't give the helper any data to work with – just executable code. The helper doesn't know the name of the property the code is using. This is the point where Expression<T> is useful.

With Expressions

This version of the helper will wrap the incoming lambda with Expression<T>. The Expression<T> data type is magical. Instead of giving the helper executable code, an expression will force the C# compiler to give the helper a data structure that describes the code (my article on C# and LINQ describes this in more detail).

The HTML helper can use the data structure to find all sorts of interesting things, like the property name, and given the name it can get the value in different ways.

代码语言:javascript
复制
// this code demonstrates a point, don't use it for real work
public static IHtmlString MyTextBox<T, TResult>(
    this HtmlHelper<T> helper,
    Expression<Func<T, TResult>> expression)
{
    var builder = new TagBuilder("input");           
    builder.MergeAttribute("type", "text");
 
    // note – not always this simple
    var body = expression.Body as MemberExpression;
    var propertyName = body.Member.Name;           
    builder.MergeAttribute("name", propertyName);
 
    var value = "";
    var model = helper.ViewData.Model;
    if (model != null)
    {
        var modelType = typeof(T);
        var propertyInfo = modelType.GetProperty(propertyName);
        var propertyValue = propertyInfo.GetValue(model);
        value = propertyValue.ToString();
    }

    builder.MergeAttribute("value", value);
 
    return new HtmlString(
        builder.ToString(TagRenderMode.SelfClosing)
    );
}

The end result being the HTML helper gets enough information from the expression that all we need to do is pass a lambda to the helper:

代码语言:javascript
复制
@Html.MyTextBox(m => m.Rating)

Summary

The lambda expressions (of type Expression<T>) allow a view author to use strongly typed code, while giving an HTML helper all the data it needs to do the job.

Starting with the data inside the expression, an HTML helper can also check model state to redisplay invalid values, add attributes for client-side validation, and change the type of input (from text to number, for example) based on the property type and data annotations.

That's why all the lambdas.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-12-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Why All The Lambdas?
    • Start From The Top
      • Without Lambdas
        • With Lambdas
          • With Expressions
            • Summary
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档