spa*_*reo 5 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2
在MVC2中,我曾经以一种方式创建强类型视图,当我发布时,我从未使用过FormCollection对象.我的签名总是这样:
[AcceptVerbs(HttpVers.Post)]
public Create(Person newPerson)
{
//code to update the person from the post
}
Run Code Online (Sandbox Code Playgroud)
但是现在我看到了这个新的TryUpdateModel方式,我只想写下这样的东西:
[AcceptVerbs(HttpVers.Post)]
public Create()
{
Person thePersonToCreate = new Person()
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在看来我必须模拟HTTPContext才能测试这个方法.但是,似乎我仍然可以使用强类型方法的前一种方式.我意识到TryUpdateModel方法对那些使用FormCollection方法的人来说是一种改进,但为什么还要使用TryUpdateModel?
在某些情况下这是可取的。一个很好的例子是当您的模型需要更复杂的初始化或工厂方法来创建时。
[AcceptVerbs(HttpVers.Post)]
public Create()
{
var dataAccess = new MyDataAccess("Another Param");
Person thePersonToCreate = new Person(dataAccess);
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
Run Code Online (Sandbox Code Playgroud)
现在,有人可能会说自定义 ModelBinder 是一种更好的解决方案,但如果这是一次性的情况,那么这可能会付出更多的努力而不值得。此外,将此详细信息隐藏在 ModelBinder 中会使错误更难以调试。
我确信还有其他情况,但这只是一个简单的例子。
| 归档时间: |
|
| 查看次数: |
401 次 |
| 最近记录: |