Search code examples
c#asp.netasp.net-mvcpostcustom-model-binder

Custom model binder - get post variables with same name?


I'm building a custom model binder in ASP.NET, and in my post variables I have couple of them with same name. Example: website.com?person=1&person=3&person=6

Currently I'm using request.Form.Get("name") syntax to get variables, but it returns string, not list of strings, which I need. How can I get all variables in list?


Solution

  • You can use this code in your model binder:

    var request = controllerContext.RequestContext.HttpContext.Request;
    string[] values = request.Params.GetValues("Name");
    

    Note:

    • Request.Params gets a combined collection of QueryString, Form, Cookies, and ServerVariables items, and this way you can use your model binder for both query string and form data.

    • GetValues gets the values associated with the specified key from the collection.