VB.NET Parse Query String to Array

前端 未结 2 1538
眼角桃花
眼角桃花 2021-01-20 14:54

I have this string:

1=True&2=150+minutes&3=True&4=True&5=Continuing+to+smoke

How can I get it into an array or object like

相关标签:
2条回答
  • 2021-01-20 15:18

    The string you have is a QueryString, not a JSON string. Thus, you can use

    • HttpUtility.ParseQueryString

    to convert it into a NameValueCollection.


    Example:

    Dim s = "1=True&2=150+minutes&3=True&4=True&5=Continuing+to+smoke"
    
    Dim parsed = HttpUtility.ParseQueryString(s)
    
    For Each key In parsed
        Console.WriteLine(key & ": " & parsed(key))
    Next
    

    Output:

    1: True
    2: 150 minutes
    3: True
    4: True
    5: Continuing to smoke
    
    0 讨论(0)
  • 2021-01-20 15:30

    Well firstly, your error occurs because your attempting to parse a key/value pair string as a JSON object (which it obviously isn't). Secondly, your using MVC, there should be no need for any manual serialization server side, let the ASP.NET MVC model binder do that for you. Introduce a view model for your action e.g.

    Public Class QuizScoreViewModel
    
        Property Property1 As String
        Property Property2 As String
        ...
    
    End Class
    

    Then update your action parameter to expect QuizScoreViewModel e.g.

    <HttpPost()>
    Function GetQuizScore(ByVal viewModel As QuizScoreViewModel) As JsonResult
    
        Debug.Print(viewModel.Property1)
        ...
    
    End Function
    
    0 讨论(0)
提交回复
热议问题