MVC-如何获取ListBox所选项目';s在控制器中的值

本文关键字:控制器 项目 选项 何获取 获取 ListBox MVC- | 更新日期: 2023-09-27 18:27:40

我有一个应用程序,它有两个列表框:

 @using (Html.BeginForm())
        {
           @Html.ListBoxFor(m => m.SelectedAttributes, Model.Attributes, new {id="listBoxAvail", SIZE = 5} ) 
            <button type="button" id="add">MoveRight</button>
            <button type="button" id="remove">"MoveLeft"></button>
            <button type="button" id="remove-all">RemAll</button>
            <button type="button" id="select-all">SelAll</button>
            <button type="button" id="up" onclick="MoveUp()">Up</button>
            <button type="button" id="down" onclick="MoveDown()">Down</button>
            @Html.ListBoxFor(m => m.SelectedAttributes2, Model.SelectedItems, new { id = "listBoxSel", SIZE = 5})
            <br />
            <p>Item Caption Text (140 Characters. HTML not allowed.)</p>
            @Html.TextAreaFor(m => m.ItemCaptionText)
            <input type="submit" id="submit"  value="Save"/>
        } 

我使用jQuery将选定的值从一个列表框转移到另一个列表盒,但我在值后面加上一个"L"以供以后使用:

$("#add").click(function () {
                $("#listBoxAvail > option:selected").each(function () {
                    $(this).remove();
                    val = $(this).val();
                    temp = $(this);
                    temp.val('L' + val)
                    $(temp).appendTo("#listBoxSel");
                });
            });

使用F12开发人员工具转移到右侧列表框后,我会看到文本和值。我想知道的是如何从控制器中的C#代码中获得该值

[HttpPost]
        public ActionResult Index(OptInViewModel viewModel)
        {
            AttributeEntities db = new AttributeEntities();
            IEnumerable<string> items = viewModel.SelectedAttributes2;
            foreach (var item in items)
            {
                var temp = item;
                // Save it
                SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute();
                attribute.CustomLabel = viewModel.ItemCaptionText;
                //attribute.IsVisible = ?
                //attribute.OrderNumber = ?
                //attribute.HarmonyAttribute_ID
            }
            return View("Index");
        }

ViewModel是:

public class OptInViewModel
    {
        public IEnumerable<string> SelectedAttributes { get; set; }
        public IEnumerable<string> SelectedAttributes2 { get; set; }
        public IEnumerable<SelectListItem> Attributes { get; set; }
        public IEnumerable<SelectListItem> SelectedItems { get; set; }
        public string ItemCaptionText { get; set; }
    }

MVC-如何获取ListBox所选项目';s在控制器中的值

我不完全理解你的问题,但据我所知,你正试图将参数传递给MVC中的函数调用。参数可以像在PHP中一样添加到URL中。

例如,一个函数可以定义为

void Function (string value);

调用它的URL将是

~/Controller/Function?value=HelloWorld

您也可以设置路由。有关更多信息,请参阅StackOverflow上的答案:

ASP.NET MVC-将参数传递给控制器

编辑:我看到你正试图使用表单提交

确保您正确格式化视图,不要忘记:

@model Path.To.Model

和控制器信息:

using (@Html.BeginForm("myMethod", "Controller", FormMethod.Post))