在第二个下拉列表中显示与第一个下拉列表所选项对应的值

时间:2011-07-30 20:17:55

标签: jquery jquery-ui asp.net-mvc-2

表单包含使用以下代码创建的两个下拉列表。 两个下拉列表元素都具有属性Alusdok。 如果选择了第一个下拉列表中的项目,则第二个下拉列表应仅显示其Alusdok项目 属性与第一个下拉列表中选择的项目Alusdok属性具有相同的别名。

两个列表都很小,包含1-30个元素。哪个是最好的用户界面? 如何实现这个,可以应用一些jQuery魔法还是其他想法?

<%= Html.DropDownList("_Report", Model.Reports, new { size = 10 })%>
<%= Html.DropDownList("_Paring", Model.Parings, new { size = 10 })%>


viewmodel:

    public class ReportViewModel : ViewModelBase
    {
public List<SelectListItem> Reports { get; set; }
public string _Report { get; set; }
public List<SelectListItem> Parings { get; set; }
public string _Paring { get; set; }

public ReportViewModel() {
...
            Reports = new List<SelectListItem>();
            foreach (ReportElem r in GetReportList())
                Reports.Add(new SelectListItem { Text = r.Nimetus, Value = r.Alusdok + r.Jrk.ToString() });

            Parings = new List<SelectListItem>();
            foreach (ParingElem p in GetParings())
                Parings.Add(new SelectListItem { Text= p.DisplayName, Value= p.Id.ToString() });
        }
    }


public class ReportElem {
  public string Nimetus,Alusdok;
  public int Jrk;
  }

public class ParingElem {
  public string DisplayName, Alusdok;
  public int Id;
  }

我正在使用ASP.NET MVC2,jQuery,jQueryUI

1 个答案:

答案 0 :(得分:0)

您可以创建一个接受ReportElem.Alusdok值的操作,并返回ParingElem个对象的JSON列表。

[HttpPost]
public ActionResult GetParingElems(string parentAlusdok)
{
    // construct a list formatted like this from your data layer, etc
    List<ListItem> list = new List<ListItem>() {
        new ListItem() { Value = "1", Text = "Alusdok 1" },
        new ListItem() { Value = "2", Text = "Alusdok 2" },
        new ListItem() { Value = "3", Text = "Alusdok 3" }
    };

    return Json(list);
}

然后,您可以使用jQuery调用此操作并填充第二个下拉列表。看起来你的下拉列表有ID:_Report_Paring,所以我假设如下。

$('#_Report').change(function() {
    $.ajax({
        url: 'GetParingElems',
        type: 'POST',
        data: { parentAlusdok: $('#_Report').val() },
        dataType: 'json',
        success: function(data) { // this is the returned JSON list
            $('#_Paring').remove();
            // iterate over data
            // i and optionData are arbitrary variable names
            $.each(data, function (i, optionData) {
                $('#_Paring').append(
                    $('<option></option>').val(optionData.Value).html(optionData.Text)
                );
            });
        }
    });
});

请记住,您可能需要修改路由(可能在global.asax中)以接受/ControllerName/GetParingElems/{parentAlusdok}形式的请求。如果您的操作位于另一个控制器等,您可能还需要调整url调用的$.ajax参数。

相关问题