在 MVC2 中,我曾经以一种在发布时从未使用过 FormCollection 对象的方式创建强类型 View 。我的签名总是这样:
[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 烦恼呢?
最佳答案
有些情况下这是可取的。一个很好的例子是当您的模型需要更复杂的初始化或工厂方法来创建时。
[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
}
}
现在有人可能会争辩说,自定义 ModelBinder 在这里是一个更好的解决方案,但如果这是一次性的情况,那可能会付出更多的努力而不值得。此外,在 ModelBinder 中隐藏此细节会使错误更难以调试。
我确定还有其他情况,但这只是一个简单的例子。
关于asp.net-mvc - TryUpdateModel 与强类型方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7639511/