【问题标题】:TryUpdateModel vs. strongly typed method parameterTryUpdateModel 与强类型方法参数
【发布时间】:2011-10-04 03:58:40
【问题描述】:

在 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 呢?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2


    【解决方案1】:

    在某些情况下这是可取的。一个很好的例子是当您的模型需要更复杂的初始化或创建工厂方法时。

    [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 中会使错误更难以调试。

    我确定还有其他情况,但这只是一个简单的示例。

    【讨论】:

      【解决方案2】:

      当您必须首先将信息加载到实体中并合并您的值以进行验证时,有些人也会使用该方法。但是,在这些情况下您可以只使用 automapper,但有些公司禁止开源代码。

      我认为几乎没有人在架构良好的应用程序中使用 FormCollection。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-11
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2019-10-27
        • 1970-01-01
        • 2010-11-15
        • 1970-01-01
        相关资源
        最近更新 更多