对IModelBinder.BindModel的调用是否已经设置了bindingContext.Model / ModelMetadata?

时间:2012-06-20 10:47:33

标签: asp.net-mvc asp.net-mvc-3 model model-binding

盲目地覆盖绑定上下文的ModelMetaData以设置模型的类型是否安全?我担心在编辑场景中可能会使用活页夹来更新预先构建的模型,如果我只是覆盖ModelMetaData,我将丢失数据。

示例代码:

Public Class CustomModelBinder
    Inherits DefaultModelBinder

    Public Overrides Function BindModel(ByVal controllerContext As ControllerContext, ByVal bindingContext As ModelBindingContext) As Object
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(Nothing, GetSpecificModelTypeBasedOnBindingData(bindingContext))

        Return MyBase.BindModel(controllerContext, bindingContext)
    End Function
End Class

1 个答案:

答案 0 :(得分:1)

是的,可能已经指定了模型。例如,当有人尝试使用TryUpdateModel / UpdateModel更新现有模型时会发生这种情况,如此处所示。

public ActionResult Update(int id)
{
   var modelToUpdate = GetExistingModel(id);

   if (TryUpdateModel(modelToUpdate)) // replacing the Model or ModelBinderContext.Metadata in the model binder could have unexpected and unwanted results.
   {
      // etc.
   }

   // etc.
}