MVC Razor get option value from select with FormCollection

若如初见. 提交于 2019-11-29 12:55:58

问题


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.


回答1:


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"];
    }



回答2:


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

    String role = formCollection["inputRole"];


来源:https://stackoverflow.com/questions/21303236/mvc-razor-get-option-value-from-select-with-formcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!