Is POSTing a Dictionary to an .NET MVC action possible?

前端 未结 3 555
轻奢々
轻奢々 2021-02-07 20:50

I have a form which contains a series of fields like:




        
相关标签:
3条回答
  • 2021-02-07 21:45

    See http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx for the syntax necessary to bind to a dictionary. Note in particular the example of binding MSFT + AAPL company tickers around halfway down that post.

    0 讨论(0)
  • 2021-02-07 21:45

    For ASP.NET MVC 2 use this:

    <input type="hidden" name="User[0].Key" value="123" />
    <input type="text" name="User[0].Value" value="Alice" />
    
    <input type="hidden" name="User[1].Key" value="456" />
    <input type="text" name="User[1].Value" value="Bob" />
    

    You need an extra hidden field User[i].Key. i is zero-based index. It should be uninterrupted.

    when you model bind to a dictionary, you're actually binding to an ICollection<KeyValuePair<,>>. So you need User[x].Key and User[x].Value (to reconstitute the KeyValuePair object)

    References

    • ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries by Scott Hanselman
    • ASP.NET MVC Model Binding Form Inputs To Action Parameters by Marco Magdy
    0 讨论(0)
  • 2021-02-07 21:49

    It's possible for lists, I'm sure it carries over for dictionaries as well. Read through Model Binding to a List by Phil Haack for some understanding on how list binding works.

    You should be able to do this:

    <input type="hidden" name="User.Index" value="123" />
    <input type="text" name="User[123]" value="Alice" />
    
    <input type="hidden" name="User.Index" value="456" />
    <input type="text" name="User[456]" value="Bob" />
    
    0 讨论(0)
提交回复
热议问题