Html MVC Razor 使用 FormCollection 从选择中获取选项值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21303236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:39:15  来源:igfitidea点击:

MVC Razor get option value from select with FormCollection

htmlasp.net-mvcselectrazorformcollection

提问by Lord Vermillion

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

我的视图有一个来自我的 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.

这给了我一个空值。

回答by Nitin Varpe

Try this to get the value of control in the formcollection

试试这个来获取formcollection中控件的值

formCollection["inputRole"]

Your code becomes

你的代码变成

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

回答by Usman

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

您可以通过其名称以这种方式简单地访问您的表单字段

    String role = formCollection["inputRole"];