如何将多选框中动态创建的选项传递给MVC控制器

时间:2015-06-16 17:40:14

标签: javascript c# jquery asp.net-mvc asp.net-mvc-4

请帮忙。我正在使用MVC,razor 3,jquery。 当下拉选择更改时,我会动态创建一个多选框。我将多个选择绑定到我的模型中的List。并且它有效,除了它传递了所选indice的列表,而不是所选文本的列表。我想要选择的文本,而不是列表的索引。我将值设置为文本,但我没有运气。

如果我手动创建列表,一切正常。如何将所选选项列表传递回控制器?

我认为我有这个div:

    <div class="row-fluid" id="divAvailableAssemblies"  hidden ="hidden">
    <label class="span4">Available Assemblies:</label>
    <select multiple="multiple" class="span8 ui-corner-all" id="Request_SelectingAssemblies" name="Request.SelectingAssemblies">
        @*<option value="test">test</option>
        <option value="test2">test2</option>*@

    </select>

</div>

这是我的jquery:

<script type="text/javascript">
$(function () {
    $('#ddPartsToCreate').live('change',function () {
        var selectedPart = this.value;
        if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
        {
            $("#divAvailableAssemblies").attr("hidden", "hidden");
            return;
        }

        $("#divAvailableAssemblies").removeAttr("hidden");

        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetSelectingAssembliesFromOrder", "Home")',
            data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            async: false,
            success: function (response) {
                var returnedData = JSON.parse(response);

                var selectingAssemblies = $("#Request_SelectingAssemblies");

                selectingAssemblies.empty();

                for (var assembly in returnedData)
                {
                    //selectingAssemblies.append($('<option >', { value: assembly }).text(returnedData[assembly].Text)).hide().show();
                    //selectingAssemblies.append($('<option value=' + assembly + '>' + returnedData[assembly].Text + '</option>'));
                    //selectingAssemblies.append($('<option >', { value: assembly, text: returnedData[assembly].Text }));
                    //selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
                    //$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));

                    //$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
                    //$('<option />', { value: assembly, text: returnedData[assembly].Text }).appendTo(selectingAssemblies);
                    selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));


                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });

});

在后端,我生成JSON:

            foreach (var assembly in pr.ShipParts)
        {
            sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assembly.Mark.ToString(), assembly.Mark.ToString()));
            availableAssemblies.Add(assembly.Mark.ToString());

        }

我在模型中使用此属性绑定多个选择(Request_SelectingAssemblies):

      public List<String> SelectingAssemblies
  {
      get
      {

          return _SelectingAssemblies;
      }
      set
      {
          _SelectingAssemblies = value;
      }
  }
  private List<String> _SelectingAssemblies = new List<string>();

当它在控​​制器中执行我的操作时,SelectingAssemblies具有索引而不是实际文本。但我将每个选项的值设置为文本。如果我手动设置选项,它们将显示在源页面中并返回文本。但是,由于我动态创建选项,因此它们不会显示在源页面中。我不知道如何让MVC理解动态数据。 在图中,动态创建了CX001,RBX001,RBX002的列表。如果我在IE中点击F12,我会在DOM中看到它们正确创建。如果我选择CX001和RBX002,SelectionAssembies将有0和2。

enter image description here 感谢

1 个答案:

答案 0 :(得分:0)

这是最新且有效的代码,感谢@StephenMuecke:

<script type="text/javascript">
$(function () {
        $('#ddPartsToCreate').live('change',function () {
        var selectedPart = this.value;
        if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
        {
            $("#divAvailableAssemblies").attr("hidden", "hidden");
            return;
        }

        $("#divAvailableAssemblies").removeAttr("hidden");

        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetSelectingAssembliesFromOrder", "Home")',
            data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            async: false,
            success: function (response) {
                var returnedData = JSON.parse(response);
                var selectingAssemblies = $("#Request_SelectingAssemblies");
                $.each(returnedData, function (index, item) {
                    selectingAssemblies.append($('<option></option>').val(item.Value).html(item.Text));
                });

            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });


});

    public ActionResult GetSelectingAssembliesFromOrder(String orderNumber)
    {
        return Json(model.GetSelectingAssembliesFromOrder(orderNumber), JsonRequestBehavior.AllowGet);
    }



    public String GetSelectingAssembliesFromOrder(String orderNumber)
    {
       //...
        StringBuilder sb = new StringBuilder();
        sb.Append("[");
        foreach (var assembly in pr.ShipParts)
        {
            string assemblyName = assembly.Mark.Trim();
            sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assemblyName, assemblyName));//JSON to build the list
            //...
        }

        sb.Append("]");
        sb.Remove(1, 1);//remove extra comma
        _db.SaveChanges();
        return sb.ToString();
    }