How does Html.EditorFor (...) know the index and the loop element?

Suppose you have a model like this:

class Foo
{
    public int A {get; set;}
    public int B {get; set;}
}

class SomeModel
{
    public List<Foo> Foos { get; set; }

}

In the ASP.NET mvc-based razor view, you can do the following:

@model SomeModel

@for(int i = 0; i < Model.Foos.Count; ++i)
{
   Html.EditorFor(x => x.Foos[i]);
}

And the razor engine will gladly spit out the correct html containing the index, and invoke the editor template with the correct indexed instance.

Method EditorForis a static extension method with signature

public static MvcHtmlString EditorFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression
)

It’s clear from the signature that it simply accepts the expression, and the only context comes from the HtmlHelper instance.

I did a very limited processing of the tree Expression, but from what I saw, I see no way that this static method could know the information that it somehow magically receives.

EditorFor html ?

+5
1

, x.Foos[i]. MVC , . , :

Html.EditorFor(x => x.Foos)

MVC .

, MVC / :

EDIT: , , :

List<string> list = new List<string>() { "A", "B", "C" };
var tester = new ExpressionTester<List<string>>(list);
var item = tester.Foo(p => p[0]);

:

public class ExpressionTester<TModel>
{
    private TModel _list;
    public ExpressionTester(TModel list)
    {
        _list = list;
    }

    public TValue Foo<TValue>(Expression<Func<TModel, TValue>> expression)
    {
        var func = expression.Compile();
        return func.Invoke(_list);
    }
}

Foo() expression . "" → "" , . Body → Method , .

+5

All Articles