绑定不适用于TryUpdateModel,但绑定却适用于Bind

时间:2018-08-28 03:06:03

标签: asp.net asp.net-mvc-5

我有一个asp.net mvc控制器,但遇到一个奇怪的问题。当我尝试使用具有白名单项目的“绑定”来绑定模型时,它工作正常,但是当我尝试使用包含属性的TryUpdateModel进行绑定时,同一件事却无法正常工作。我的代码非常标准。

public async Task<ActionResult> Index([Bind(include="firstname,lastname")]PersonModel model){
  .......
}

public async Task<ActionResult> Index(){
   var model = new PersonModel();
   var isBinding = TryUpdateModel(model,includeProperties:new[]{"firstName","lastname"})
  .......
}

即使未绑定,isBinding也会设置为true。有什么可以建议我为什么TryUpdateModel不起作用而Bind起作用。谢谢

1 个答案:

答案 0 :(得分:0)

TryUpdateModel()在第二个Index操作中不更新模型绑定状态的原因是,您可以将PersonModel的实例与firstname和{{ 1}}仍设置为空(甚至是空值)。

您可以使用此设置将模型与lastname绑定:

TryUpdateModel

或使用public async Task<ActionResult> Index([Bind(Include = "firstname, lastname")] PersonModel model) { if (TryUpdateModel(model)) { // save changes with await } return View(); } 作为替代:

FormCollection

但是,我认为最好设置一个包含所有必需属性并从那里绑定的viewmodel,因为public async Task<ActionResult> Index(FormCollection form) { var model = new PersonModel(); if (TryUpdateModel(model, string.Empty, new [] { "firstname", "lastname" }, null, form)) { // save changes with await } return View(); } 方法has security note you should pay attention to

TryUpdateModel()

相关问题:

How do I edit a FormCollection value, and then use TryUpdateModel with the edited collection?

When and why do you use TryUpdateModel in asp.net mvc 2?

Using TryUpdateModel to save an object on Edit Post with FormCollection