博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Why All The Lambdas?
阅读量:6788 次
发布时间:2019-06-26

本文共 7568 字,大约阅读时间需要 25 分钟。

Why All The Lambdas?

Tuesday, November 27, 2012

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

@Html.TextBoxFor(model => model.Rating)

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

@Html.TextBoxFor(Model.Rating)

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

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:

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.

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 .  Let's start with a naïve helper to create a text input.

// this code demonstrates a point, don't use it public static IHtmlString MyTextBox
( this HtmlHelper
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:

@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.

@Html.MyTextBox("Rating")

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

// this code demonstrates a point, don't use it for real work public static IHtmlString MyTextBox
( this HtmlHelper
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.

// this code demonstrates a point, don't use it for real work public static IHtmlString MyTextBox
( this HtmlHelper
helper, Func
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.

@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  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.

// this code demonstrates a point, don't use it for real work public static IHtmlString MyTextBox
( this HtmlHelper
helper, Expression
> 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:

@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.

转载地址:http://wqigo.baihongyu.com/

你可能感兴趣的文章
Working with System Properties
查看>>
为什么我墙裂建议大家使用枚举来实现单例
查看>>
记一次阿里云服务器安装Python的血泪史
查看>>
c++函数模块与其相关内容
查看>>
ssh防止暴力破解之fail2ban
查看>>
LNMP基础安装配置
查看>>
借助Gradle Plugin解决模块化开发中模块如何对外暴露接口
查看>>
深圳车牌识别助力汽车检测,颠覆传统方式
查看>>
tomcat,tomcat7配置https
查看>>
Linux进程管理
查看>>
rpm命令管理程序包
查看>>
小米6.0系统(亲测有效)激活Xposed框架的步骤
查看>>
我的友情链接
查看>>
JMX对weblogic的监控指标小结
查看>>
Image Map的制作
查看>>
solaris 11 中SAP的启动和停止
查看>>
centOS 6.2 升级 kernel 3.2.9
查看>>
jenkins构建shell或者python脚本中含有远程登录复制会报错解决办法
查看>>
python脚本 字符串变量 强制 不转义 win地址 不转义输出
查看>>
IT自学要走远,更要走深
查看>>