Advertisement
Guest User

ASP.NET MVC Json ModelBinder

a guest
Jan 27th, 2012
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.74 KB | None | 0 0
  1. Imports System
  2. Imports System.IO
  3. Imports System.Linq
  4. Imports System.Collections.Generic
  5. Imports System.Web.Helpers
  6. Imports System.Web.Mvc
  7.  
  8. Public Class DynamicJsonAttribute
  9.    Inherits CustomModelBinderAttribute
  10.  
  11.    Public Property MatchName As Boolean
  12.  
  13.    Public Overrides Function GetBinder() As System.Web.Mvc.IModelBinder
  14.       Return New DynamicJsonBinder(MatchName)
  15.    End Function
  16.  
  17. End Class
  18.  
  19. Public Class DynamicJsonBinder
  20.    Implements IModelBinder
  21.  
  22.    Private ReadOnly matchName As Boolean
  23.  
  24.    Sub New(matchName)
  25.       Me.matchName = matchName
  26.    End Sub
  27.  
  28.    Public Function BindModel(controllerContext As System.Web.Mvc.ControllerContext, bindingContext As System.Web.Mvc.ModelBindingContext) As Object Implements System.Web.Mvc.IModelBinder.BindModel
  29.       Dim contentType = controllerContext.HttpContext.Request.ContentType
  30.       If Not contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) Then
  31.          Return Nothing
  32.       End If
  33.       Dim bodyText As String
  34.       Using myStream As IO.Stream = controllerContext.HttpContext.Request.InputStream
  35.          myStream.Seek(0, SeekOrigin.Begin)
  36.          Using myReader As New StreamReader(myStream)
  37.             bodyText = myReader.ReadToEnd()
  38.          End Using
  39.       End Using
  40.  
  41.       If (String.IsNullOrEmpty(bodyText)) Then
  42.          Return Nothing
  43.       End If
  44.  
  45.       Dim parsed = Json.Decode(bodyText)
  46.       If Not matchName Then
  47.          Return parsed
  48.       End If
  49.       Dim members As IEnumerable(Of String) = parsed.GetDynamigMemberNames()
  50.       If members Is Nothing OrElse members.Contains(bindingContext.ModelName) Then
  51.          Return parsed(bindingContext.ModelName)
  52.       End If
  53.       Return Nothing
  54.    End Function
  55.  
  56. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement