0

I have a select with multiple items, and allow the user to select multiple options:

<select id="Emails" style="width: 100%;" size="16" multiple>
     @foreach (var email in Model._Emails)
     {
        @:<option value="@email.Id">@email.Adress</option>
     }
</select>

I want to get the selected options with the Request.Form:

    [HttpPost]
    public ActionResult Person(personobject obj)
    {
        IEnumerable<string> selectedemails = Request.Form["Emails"]; //Selected Emails
        ....
    }

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
Airton Gomes de Lima
  • 1,317
  • 12
  • 19
  • You could solve this using the [Html.DropDownListFor helper method](https://msdn.microsoft.com/en-us/library/ee703573.aspx), see e.g. [this](http://stackoverflow.com/questions/3057873/how-to-write-a-simple-html-dropdownlistfor) StackOverflow question. – Christian Feb 21 '15 at 21:07

2 Answers2

4

Request.Form["Emails"] will return a comma separated string of all the selected options.

You need to change your code to IEnumerable<string> selectedemails = Request.Form["Emails"].split(",");

Rafie
  • 121
  • 2
0

Your <select> tag does not have a name attribute so its value will not be posted back. Modify the html to

<select name="Emails" id="Emails" style="width: 100%;" size="16" multiple>
  ....

I recommend you learn to use view models for what you want to display/edit and html helpers to generate the correct html and allow 2 way model binding.

  • It worked, but not as i expected. Actually I want to get the attributes, but the post dispose only the value of each option. I think i gonna need to post via Ajax or put some script to serialize the attributes of each option. Thanks :) – Airton Gomes de Lima Feb 23 '15 at 11:21
  • What do you mean the _"attributes of each option"_? The value of `Emails` will be an array containing the selected options values (in you case the selected `email.Id`'s). You don't have (at least have not shown) any other attributes. What other information are you hoping to post? (and yes, you will need javascript to post back anything other than a controls value) –  Feb 23 '15 at 11:27
  • There an option on form to check the e-mail as principal, so the result it's something like this: – Airton Gomes de Lima Feb 23 '15 at 11:38
  • Since you must be generating that option server side, you already know that an `email.id` with a value of `1` has `is_principal="true"` when you post back so what is the point of sending it in the request? And its invalid html anyway. –  Feb 23 '15 at 22:32