Getting a SELECT MULTIPLE element to pass its multiple values into an array, after a POST.

Hi experts,

I’m having trouble getting a SELECT MULTIPLE element to pass its multiple values into an array, after a POST.

Basically it’s this question:

But how do I pass it into an array in ASP.NET C# syntax? Is it possible?

Currently, I have this code:

        String [] countryID ;
        if (IsPost) {
                countryID = Request.Form["country[]"]; 

<select multiple size="10" name="country[]" style="width: 200px;">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>

Open in new window

 When I run the file, I get this error.

CS0029: Cannot implicitly convert type 'string' to 'string[]'

Open in new window

Apparently, the POST operation is passing the country element as a string. I need it to pass as an array, as the link talks about in PHP.

I assume I can’t do this with ASP.NET C#, am I correct? Do I need PHP to do this?

Who is Participating?
Robert SchuttConnect With a Mentor Software EngineerCommented:
I don't think using "[ ]" in the select name is necessary. The values are posted in 1 form field, separated by commas. In older environments (Classic ASP) I've always used Split to get an array from that value. It still seems to work:
countryID = Request.Form["country[]"].Split(new char[] {','}, StringSplitOptions.None);

Open in new window

Or of course if you remove the [] from the aspx then also do that here:
countryID = Request.Form["country"].Split(new char[] {','}, StringSplitOptions.None);

Open in new window

capturePS: you seem to be using MVC/Razor or something like that, I don't have much experience with that so I tested in a 'plain' project. Hopefully that doesn't make my contribution void...
nvs_victorAuthor Commented:
Hi  robert_schutt!

Thanks for your prompt help!

Strangely, today, it's working as expecting... producing a comma separated value.

Yesterday, without the array [] thing, it was only displaying the correct value if only one item was selected, but when multiple items were selected, it would display 0. Hence why I asked this question.

Strange. I don't recall anything I did differently from yesterday.

But it is good news :)

Thanks for your help!
nvs_victorAuthor Commented:
I can't even reproduce what I saw yesterday with the zero thing... bizarre!
nvs_victorAuthor Commented:
robert_schutt helped me assure me that it will pass comma separated.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.