3

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?

Faruk Ljuca
  • 78
  • 1
  • 6

2 Answers2

3

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.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
1

request.Form.Get("person") will give you a string. But if you have more than one form elements with same name ,person, It will give you a comma separated string of values for items with person name. So you need to create an array from that using Split() method.

var s = request.Form.Get("person");  // s will have the value like "shyju,scott,sam"
var personArray= s.Split(',');
Shyju
  • 214,206
  • 104
  • 411
  • 497