MVC Razor get option value from select with FormCollection
Asked Answered
N

2

11

My view has a Select with elements(options) from my ViewModel.

        @using (Html.BeginForm("NewUser", "Admin"))
        {
             <select multiple="" id="inputRole" class="form-control" size="6" name="inputRole">
             @foreach (var item in Model.roller)
             {
                 <option>@item.Name</option>
             }
             </select>
         }

How can i get the selected value in my Controller?

    [HttpPost]
    public ActionResult NewUser(FormCollection formCollection)
    {
        String roleValue1 = formCollection.Get("inputRole");
    }

This gives me a null value.

Nostradamus answered 23/1, 2014 at 8:43 Comment(0)
S
22

Try this to get the value of control in the formcollection

formCollection["inputRole"]

Your code becomes

[HttpPost]
    public ActionResult NewUser(FormCollection formCollection)
    {
        String roleValue1 = formCollection["inputRole"];
    }
Savina answered 23/1, 2014 at 8:57 Comment(0)
C
6

You can simply accesss your form field by its name in that way

    String role = formCollection["inputRole"];
Crawly answered 23/1, 2014 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.