mvc @html.editorfor,c# - @Html.EditorFor(m => m) lambda syntax in MVC - Stack Overflow

Let's break this down by examining the method signature:

MvcHtmlString EditorFor(

this HtmlHelper html,

Expression> expression

)

This is using extension method syntax, which means it's adding a method named EditorFor to HtmlHelper such that you can make the call Html.EditorFor. But what we're really interested in is the second parameter, Expression>. That's a pretty complicated parameter, but for now we can ignore the fact that it's an Expression. So simplifying, let's examine:

Func expression

This means that the argument is any method that has one parameter (of type TModel) and the return type is TValue. You've been using lambdas, which is (essentially) a more concise representation of a method, but it's helpful to just think of it as an ordinary method. So you're lambda is taking a model and returning a model:

m => m

That's not as interesting, so let's compare it to a more realistic scenario where you're returning a property off the model:

m => m.MyStringProperty

Now let's compare it with an ordinary static method you've declared somewhere:

public static class MyStaticClass

{

public static string Foo(TModel model)

{

return model.MyStringProperty;

}

}

Although really here it wouldn't be TModel -- it would be whatever you declared your model type via @model. Now, for the sake of discussion, you could have instead used this method in your invocation of EditorFor:

Html.EditorFor(MyStaticClass.Foo);

So to sum up, lambdas are (for the most part) just a short hand for a regular method. So all you're doing is passing methods around.

The last note here is that we are actually using expression trees, which means you aren't actually passing the method, you're passing an object model (an expression tree) that represents the code of the method. This is, essentially, just used to figure out the property name you're using (because usually the lambda would be more like m => m.MyProperty, not merely m => m). This is all to avoid magic strings where you refer to the property name by using a string (i.e. "MyProperty").

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值