Let's break this down by examining the method signature:
MvcHtmlString EditorFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> 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<Func<TModel, TValue>>
. 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<TModel, TValue> 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").
EditorFor
is an extension method, so you're looking for the one overload with two parameters, the first being "this". – Solomon@Html.TextBoxFor(m => m.name)
this is so that if you ever want a default value it will work. Where I (at least) have not been able to assign this to anEditorFor
. Also TextBox/TextArea etc support placeholders among other things whereEditorFor
does not. so you could do@Html.TextBoxFor(m=>m.Name, new { placeholder = "John Doe" })
and mvc will automatically implement a placeholder in browsers that support it. – Pitts