Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor get option value from select with FormCollection

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.

like image 678
Lord Vermillion Avatar asked Jan 23 '14 08:01

Lord Vermillion


2 Answers

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"];
    }
like image 162
Nitin Varpe Avatar answered Sep 29 '22 17:09

Nitin Varpe


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

    String role = formCollection["inputRole"];
like image 38
Usman Avatar answered Sep 29 '22 16:09

Usman