简体   繁体   English

ASP.NET MVC 2模型绑定程序背后的幕后

[英]Asp.net mvc 2 model binders what's behind scene

Im starting with MVC2 and i have a simple question: 我从MVC2开始,我有一个简单的问题:

If i have a typed view with a form inside, and this textbox created with lambda expressions: 如果我有一个带有窗体的类型化视图,并且此文本框是使用lambda表达式创建的:

 <%: Html.TextBoxFor(e => e.Name)%>

When i submit this form the default model binder take the request form, takes the model typed to the view, serialize the data posted (as a this model) and pass it to an action of my controller. 当我提交此表单时,默认模型绑定器采用请求表单,将键入的模型带到视图,序列化发布的数据(作为此模型),并将其传递给我的控制器的操作。

To try to explain myself better, lets imagine that i have a url like localhost/edittestmodel/ID/1 and i have in my controller action the following code: 为了尝试更好地解释自己,让我们想象一下,我有一个类似localhost / edittestmodel / ID / 1的URL,并且在我的控制器操作中有以下代码:

public ActionResult Edit(int id)
{
    TestModel testmodel=new TestModel();
    testmodel.Name="texttorenderintotextbox";
    //whats the class that place the testmodel properties into the view? 
    return View(testmodel);

}

What's the responsable class for place the Name property of my testmodel object into the textbox 将我的testmodel对象的Name属性放入文本框的负责任的类是什么

<%: Html.TextBoxFor(e => e.Name)%>

Thanks in advance. 提前致谢。

Best Regards. 最好的祝福。

Jose. 何塞

正是TextBoxFor helper方法负责从lambda表达式生成输入字段。

View's don't have anything to do in POST request and model binding View在POST请求和模型绑定中无事可做

When you have strong type views, model type is barely used to have the simplicity of code intellisense in view's code (so you can use lambda expressions like in your example). 当您拥有强大的类型视图时,很少使用模型类型来简化视图代码中的代码智能化(因此您可以像示例中那样使用lambda表达式)。

But when you POST data back, nothing gets checked against the view. 但是,当您回传数据时,不会对视图进行检查。 It gets checked against controller action parameters though. 但是,它会根据控制器操作参数进行检查。 And if there's a parameter with a certain custom model binder type, that particular model binder is used to process incoming data. 并且,如果存在具有特定自定义模型绑定程序类型的参数,则使用该特定模型绑定程序来处理传入的数据。

But to answer your question : TextBoxFor checks your strong type view's model and generates particular textbox with correct name attribute. 但是要回答您的问题TextBoxFor检查您的强类型视图的模型并生成具有正确名称属性的特定文本框。 So data from it will be posted back under the correct form field name. 因此,来自其中的数据将以正确的表单字段名称回发。

To go even deeper. 更加深入。 It's the view engine that parses view's ASPX code and runs all server side scripts including Html.TextBoxFor() call. 视图引擎解析视图的ASPX代码并运行所有服务器端脚本,包括Html.TextBoxFor()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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