TryUpdateModel 与强类型方法参数
在 MVC2 中,我曾经以一种在发布时从未使用过 FormCollection 对象的方式创建强类型视图。我的签名总是看起来像这样:
[AcceptVerbs(HttpVers.Post)]
public Create(Person newPerson)
{
//code to update the person from the post
}
但现在我看到了这种新的 TryUpdateModel 方式,我只需编写如下内容:
[AcceptVerbs(HttpVers.Post)]
public Create()
{
Person thePersonToCreate = new Person()
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
所以现在看来我必须模拟 HTTPContext 才能测试此方法。但是,似乎我仍然可以使用前一种使用强类型方法的方式。我意识到 TryUpdateModel 方法对于那些使用 FormCollection 方法做事的人来说是一种改进,但为什么还要费心使用 TryUpdateModel 呢?
In MVC2 I used to create strongly typed views in a way that when I posted, I never used the FormCollection object. My signatures always looked like so:
[AcceptVerbs(HttpVers.Post)]
public Create(Person newPerson)
{
//code to update the person from the post
}
But now I'm seeing this new TryUpdateModel way where I would just write something like:
[AcceptVerbs(HttpVers.Post)]
public Create()
{
Person thePersonToCreate = new Person()
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
So now it seems I have to mock up the HTTPContext in order to test this method. However, it seems like I can still use the former way using strongly typed methods. I realize that the TryUpdateModel method is an improvement for those who would use the FormCollection method of doing things but why bother with TryUpdateModel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在某些情况下这是可取的。一个很好的例子是当您的模型需要更复杂的初始化或工厂方法来创建时。
现在,有人可能会认为自定义 ModelBinder 是一种更好的解决方案,但如果这是一次性情况,那么可能会付出更多的努力而不值得。此外,将此详细信息隐藏在 ModelBinder 中会使错误更难以调试。
我确信还有其他情况,但这只是一个简单的例子。
There are instances where this is desirable. A good example is when your model requires a more complex initialization, or factory method to create.
Now one might argue that a custom ModelBinder is a better solution here, but that might be more effort than it is worth if this is a one off situation. Also, hiding this detail in a ModelBinder makes errors more difficult to debug.
There are other situations I'm sure, but this is just a quick example.
当您必须首先将信息加载到实体中并合并值以进行验证时,有些人也会使用该方法。然而,在这些情况下您可以只使用 automapper,但有些公司禁止开源代码。
我认为几乎没有人在架构良好的应用程序中使用 FormCollection。
Some also use that method when you have to load information into an entity first and merge your values for validation purposes. You could however just use automapper in these cases but some companies prohibit open source code.
I would argue almost no one uses FormCollection in a well architected app.