加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:26:32 所属栏目:asp.Net 来源:网络整理
导读:在MVC2中,我曾经以一种方式创建强类型视图,当我发布时,我从未使用过FormCollection对象.我的签名总是这样: [AcceptVerbs(HttpVers.Post)] public Create(Person newPerson){ //code to update the person from the post} 但是现在我看到了这个新的TryUpdate
在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?

解决方法

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

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

还有其他情况我敢肯定,但这只是一个简单的例子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读