简体   繁体   English

ASP.NET MVC DropDownGroupList Ajax请求

[英]ASP.NET MVC DropDownGroupList Ajax Request

i have some trouble with this DropDownGroupList extension for ASP.NET MVC 5. What i try to accomplish is to populate the control using javascript and data from an ajax request. 我在使用ASP.NET MVC 5的DropDownGroupList扩展时遇到了一些麻烦。我试图完成的工作是使用javascript和来自ajax请求的数据填充控件。 So far, i was able to do that only for the DropDownList control. 到目前为止,我只能对DropDownList控件执行此操作。 Here is a small piece of my code for the DropDownList but how can i make this work for the other one? 这是我的DropDownList代码的一小部分,但是如何使另一个代码工作呢?

$("#Area").change(function () {
        $("#Station").empty();
        $("#Station").prop("disabled", true);
        if ($("#Area").val() != "Select area") {
            var AreaOptions = {};
            AreaOptions.url = "/Production/SelectArea";
            AreaOptions.type = "POST";
            AreaOptions.data = JSON.stringify({ Area: $("#Area").val() });
            AreaOptions.datatype = "json";
            AreaOptions.contentType = "application/json";
            AreaOptions.success = function (LinesList) {
                $("#Line").empty();
                $("#Line").append("<option value='Select line'>Select line</option>");
                for (var i = 0; i < LinesList.length; i++) {
                    $("#Line").append("<option value=" + LinesList[i].Value + ">" + LinesList[i].Text + "</option>");
                }
                $("#Line").prop("disabled", false);
                $("#Station").prop("disabled", true);
            };
            AreaOptions.error = function () { alert("No data for selected area!"); };
            $.ajax(AreaOptions);
        }

        else {
            $("#Line").empty();
            $("#Line").prop("disabled", true);
        }
    });


Edit 1 编辑1
OK, so here is my controller... tried to return a JsonResult so far: 好,所以这是我的控制器...到目前为止尝试返回JsonResult:

public JsonResult SelectLine()
{
    List<GroupedSelectListItem> Stations = new List<GroupedSelectListItem>();
    Stations.Add(new GroupedSelectListItem { Text = "Station 1", Value = "Station 1", GroupName = "Line 1", GroupKey = "Line 1" });
    Stations.Add(new GroupedSelectListItem { Text = "Station 2", Value = "Station 2", GroupName = "Line 1", GroupKey = "Line 1" });
    Stations.Add(new GroupedSelectListItem { Text = "Station 3", Value = "Station 3", GroupName = "Line 2", GroupKey = "Line 2" });
    Stations.Add(new GroupedSelectListItem { Text = "Station 4", Value = "Station 4", GroupName = "Line 3", GroupKey = "Line 3" });
    Stations.Add(new GroupedSelectListItem { Text = "Station 5", Value = "Station 5", GroupName = "Line 4", GroupKey = "Line 4" });
    return Json(Stations);
}

How can i bind this to a DropDownGroupList? 如何将其绑定到DropDownGroupList?

Edit 2 编辑2
Stephen Muecke works as a charm. Stephen Muecke很有魅力。 Thank you! 谢谢!

Firstly you should not be returning List<GroupedSelectListItem> which serializes all properties of GroupedSelectListItem meaning your just sending extra data across the wire which you don't even use. 首先,您不应该返回List<GroupedSelectListItem> ,它会序列化List<GroupedSelectListItem>所有属性, GroupedSelectListItem意味着您只是通过导线甚至不使用就发送了额外的数据。 I assume you not really hard coding values, and that you are really generating these from a collection of objects. 我假设您不是真正地对值进行硬编码,并且您实际上是从对象集合中生成这些值。 You have not shown your model, but lets assume you have a Person object that you want to group by gender 您尚未显示模型,但假设您有Person性别分组的Person对象。

public class Person
{
  public string ID { get; set; }
  public string Name { get; set; }
  public string Gender { get; set; }
}

and in your method you call a repository to get all persons 然后用您的方法调用存储库以获取所有人

public JsonResult SelectLine()
{
  var data = db.Persons.GroupBy(p => p.Gender).Select(p => new
  {
    group = p.Key,
    options = p.Select(o => new
    {
      text = o.Name,
      value = o.ID
    })
  });
return Json(data, JsonRequestBehavior.AllowGet);
}

In you case you seem to be using the same value for both the options text and the option value, so you should omit the value = o.ID line. 在这种情况下,选项文本和选项值似乎都使用相同的值,因此应省略value = o.ID行。

Then change the script to 然后将脚本更改为

// dont hard code urls - use Url.Action
var url = '@Url.Action("SelectLine", "Production");
// cache elements you repeatedly refer to
var stations = $('#Station');
var lines = $('#Line');
$("#Area").change(function () {
  stations.empty().prop('disabled', true);
  lines.empty();
  if (!$(this).val()) { // see notes below
    lines.prop('disabled', true);
    return;
  }
  $.getJSON(url, { Area: $(this).val() }, function(data) {
    if (!data) {
      // oops - display error message?
      return;
    }
    lines.append($('<option></option>').val('').text('Select line')); // see notes below
    $.each(data, function (index, item) {
      var group = $('<optgroup></optgroup>').attr('label', item.group);
      $.each(item.options, function (index, opt) {
        group.append($('<option></option>').val(opt.value).text(opt.text));
        // or if you want the text and value to be the same then use
        // group.append($('<option></option>').text(opt.text));
      });
      lines.append(group);
    });
  }).fail(function() {
    // oops
  });
});

Side notes: 旁注:

  1. Your label option should have a null value so that you can use client and server side validation. 您的标签选项应为空值,以便您可以使用客户端和服务器端验证。
  2. Use $(this).val() , not $("#Area").val() so you don't have to search the DOM again. 使用$(this).val() ,而不要使用$("#Area").val()这样就不必再次搜索DOM。
  3. There is no need to stringify the data and add the contentType attribute (note the code above uses the $.getJSON() shortcut) 无需对数据进行字符串化和添加contentType属性(请注意,上面的代码使用$.getJSON()快捷方式)
  4. If your using the same value for both the text and value, just set the text 如果您为文本和值使用相同的值,则只需设置文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM