简体   繁体   中英

What's the '=>' operator in ASP.NET inside a Html method used for?

I know the question is a little be tricky. I know what that operator does, but what I don't understand is, for instance, these lines of code:

<div class="editor-field">
     @Html.EditorFor(model => model.Title)
     @Html.ValidationMessageFor(model => model.Title)
</div>

The parameter of EditorFor or ValidationMessageFor, is it supposed to be a lambda or what? At first I thought, oh, it's a lambda expression (I was still confused by it, though), but then I saw this:

@foreach(var item in Model) {
 <tr>
      <td>
           @Html.DisplayFor(modelItem => item.Title);
      </td>
 </tr>
}

And then I said, I don't know, that doesn't look a lambda expression, the left side is supposed to be the parameter, and the right side what it returns (or the body), and then I said: "Uhm, alright, that ain't using the parameter,... so what the heck is that?"

I know it's a little bit of a dumb question, but I like to know how everything works.

Thanks in advance.

A HtmlHelper basicly has this definition:

public static MvcHtmlString Foo<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
    var method = expression.Compile();

    //Pass the current model as parameter to your compiled expression:
    var value = method(htmlHelper.ViewData.Model);

    //Convert the result of your Expression to a String:
    return new MvcHtmlString(value.ToString());
}

What you pass in, is of type Expression<Func<TModel, TValue>> . So yes, it is a Lamda Expression

The parameter model only passes an object (your model) as parameter. model.title returns the title of that object.

The confusion, that comes from your foreach loop with modelItem is nothing other. You are just not using modelItem .

它只是不使用lambda中的参数,该参数可以命名为任何东西,例如thisIsATotallyUselessParameterBecauseImjustgonnauseItem => item.Title

Yes, it's a regular lambda expression. I like to read a lambda as "for some variable x, do something." Usually the "do something" means do something with x , but technically you are allowed to disregard x. For example: "for some variable x, do something with items."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM