There are many things going on here. Some of which are "hidden" by the Razor rendering engine behind the scenes. For example, at the top of the page when you specify @model Foo
this actually is a syntactical shortcut to creating a class for your Page which uses Foo as it's model type. In WebForms this would look like this:
<% @Page Inherits="System.Web.Mvc.ViewPage<Foo>" %>
Razor hides this from you though. In reality, your View actually is a ViewPage<Foo>
when you use @model Foo
Now, if you look at ViewPage in the documentation:
https://msdn.microsoft.com/en-us/library/dd470798(v=vs.118).aspx
You will see a lot of interesting things. Among them is the Html property.
This is of type HtmlHelper<TModel>
where TModel is Foo if your Model is Foo.
So, when you write (in Razor) @Html.Whatever()
this is really an HtmlHeler<Foo>.Whatever()
.
https://msdn.microsoft.com/en-us/library/dd492619(v=vs.118).aspx
Now, let's look at the actual method you're concerned with. Html.TextBoxFor()
If you look at the link above for HtmlHelper, you can see a number of Extension methods on this, these extension methods are the basis for the HtmlHelpers that MVC provides. Among them is:
https://msdn.microsoft.com/en-us/library/ee703644(v=vs.118).aspx
public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
Here, we can see that this is an extension method. It takes the TModel and TProperty generic parameters, and in the function parameters is this HtmlHelper<TModel> htmlHelper
as the first parameter. C# hides this from you in extension methods, but passes it to the method when you call it as @Html.TextBoxFor()
.
Notice that the next parmeter is the expression, which is of type Expression<Func<TModel, TProperty>>
, so, this is how the expression (or lambda) knows ultimately what the model is, and knows to return the property type. It boils down to specifying the model type at the top of the page, and having this bubble down through the object graph.
I know this is a lot to absorb, but if you follow the chain of objects, you should get the hang of how this works.
As for posting back to the server, this has little to do with any of this. That is part of the model binding system, and it just looks at the values posted to the server and the type of parameter the action method takes, and then it tries to match them up based on their names.
The only thing that is related is that the HtmlHelpers format the input element names in a manner the model binder can understand.