Search code examples
c#asp.net-core-mvcasp.net-core-2.0mailchimp

Model binding POST values with square brackets


How can I bind a POSTed parameter named "data[email]" to a model in Asp.Net MVC?

Posted data:

type=subscribe&data%5Bemail%5D=my%40iemail.com

Without url encoding:

type=subscribe&data[email][email protected]

The model I want to bind to:

public class MyModel
{
  public string type {get;set;}
  public string dataemail {get;set;} //What do I do here to 
}

The method receiving the POST:

public ActionResult Post(MyModel payload)
{
    return Ok(payload);
}

Background:

MailChimp uses POST for webhooks, and posts some of the values back with square brackets in them. I can't figure out how to model bind that.

I could use Request.Form, but... Would really much rather use model binding.


Solution

  • Update the model data property to use a dictionay

    public class MyModel {
        public string type { get; set; }
        public Dictionary<string, string> data { get; set; }
    }
    

    accessing the email would be done through the dictionary like

    var email = payload.data["email"];