asp.net-mvc - TryUpdateModel 与强类型方法参数

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

在 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/

相关文章:

jquery - 这是有效的 jquery getJSON 调用吗?

Asp.Net MVC - 重载操作方法

asp.net mvc 2 Html.RenderPartial CSS

c# - MVC5/EF/LINQ - 多个选择计数查询返回到 View ,最佳实践

asp.net-mvc - Mvc3在IE7中默认授权过滤器属性

c# - WebGrid 分页不工作

c# - Asp 网络成员身份提供程序中的更改密码问题

jquery - 使用 JQuery Datepicker 选择的日期未反射(reflect)在提交时的 MVC3 模型中

.net - 数据服务抛出神秘异常 : "Media type requires a ' /' character"

asp.net-mvc-2 - Asp.net MVC 2、MvcContrib 和具有重定向操作的基本 Controller