我目前正在开发一个ASP.NET MVC3项目。
我已经实现了一个自定义的IModelBinder类。在BindModel方法中,我试图检索项目的ID(GUID),如下所示:
Public Class MyViewModelModelBinder
Implements IModelBinder
Public Function BindModel(controllerContext As System.Web.Mvc.ControllerContext, bindingContext As System.Web.Mvc.ModelBindingContext) As Object Implements System.Web.Mvc.IModelBinder.BindModel
Dim myVM As MyViewModel
If (bindingContext.Model IsNot Nothing AndAlso TypeOf bindingContext.Model Is MyViewModel) Then
myVM = DirectCast(bindingContext.Model, MyViewModel)
Else
myVM = New MyViewModel
End If
Dim proposedObjectID As Guid = GetValue(Of Guid)(bindingContext, "ObjectID")
myVM.ObjectID = proposedObjectID
'...'
Return myVM
End Function
Private Function GetValue(Of T)(ByVal bindingContext As ModelBindingContext, ByVal key As String) As T
Dim returnValue As T = Nothing
Dim valueResult As ValueProviderResult
valueResult = bindingContext.ValueProvider.GetValue(key)
If valueResult IsNot Nothing Then
Try
returnValue = DirectCast(valueResult.ConvertTo(GetType(T)), T)
Catch ex As Exception
returnValue = Nothing
End Try
End If
Return returnValue
End Function
End Class
我遇到的问题是GetValue
方法,因为bindingContext.ValueProvider.GetValue(key)
方法正在返回null
/ nothing
。可以假设这是因为ValueProvider
中的键和/或值不是,但情况并非如此...... ModelBindingContext.ValueProvider.GetValue
返回null / nothing,即使有我想要检索的项目的键和值。
我可以通过执行以下操作来检索ID:
Public Function BindModel(controllerContext As System.Web.Mvc.ControllerContext, bindingContext As System.Web.Mvc.ModelBindingContext) As Object Implements System.Web.Mvc.IModelBinder.BindModel
Dim proposedObjectID As Guid
Guid.TryParse(CType(bindingContext.ValueProvider, FormCollection)("ObjectID"), proposedObjectID)
'...'
End Function
但我很难理解为什么GetValue
方法无法正确检索值。
请你解释一下我做错了什么?
谢谢。
答案 0 :(得分:0)
我发现了问题!
我不小心在我为GetValue
方法提供的密钥末尾添加了一个空格。因此,密钥(带有附加空格)实际上并不存在于我的集合中!