根据用户选择填写组合

时间:2015-06-18 23:50:37

标签: asp.net-mvc asp.net-mvc-4

我有组合1,其中包含数量,组合2包含在组合中选择的最大值1如何在用户更改组合1后设置组合2的值

组合1:

  @Html.DropDownListFor(model => model.QtiteToBuy, new SelectList(
           new List<Object>{ 
                   new { value = 0 , text = "0"},
                   new { value = 1 , text = "1"},
                   new { value = 2 , text = "2"},
                   new { value = 3 , text = "3"},
                   new { value = 4 , text = "4"},
                   new { value = 5 , text = "5"},
                   new { value = 6 , text = "6"},
                   new { value = 7 , text = "7"},
                   new { value = 8 , text = "8"},
                   new { value = 9 , text = "9"}
                }, "value", "text"))

如果用户选择combo1 = 4,我应该在0到4的组合2中

1 个答案:

答案 0 :(得分:0)

@melom我做了sample here,应该让你开始。如果您有任何其他问题,请与我们联系。

首先总结一下我在回发时填充了combo1,然后使用ajax填充combo2。

查看:

<div>
    @Html.DropDownList("combo1", (IEnumerable<SelectListItem>)ViewBag.combo)
     <select id="combo2"></select> 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){   
        $('#combo1').change(function(){     
            $.ajax({
                type: "GET",
                url: "@Url.Action("GetSecondComboData", "Home")",
                data: { val : $(this).val() },
                success: function (data) {
                    var options = $("#combo2");
                    options.empty();
                    $.each(data, function() {
                        options.append($("<option />").val(this).text(this));
                    });
                },
                dataType: 'json'
            });     
        }); 
    });
</script>

动作:

[HttpGet]
public ActionResult Index()
{
    var values = new List<dynamic>
    {
        new { value = 0 , text = "0"},
        new { value = 1 , text = "1"},
        new { value = 2 , text = "2"},
        new { value = 3 , text = "3"},
        new { value = 4 , text = "4"},
        new { value = 5 , text = "5"},
        new { value = 6 , text = "6"},
        new { value = 7 , text = "7"},
        new { value = 8 , text = "8"},
        new { value = 9 , text = "9"}
    };

    ViewBag.combo = new SelectList(values, "value", "text");

    return View();
}

[HttpGet]
public JsonResult GetSecondComboData(int val)
{
    return Json(Enumerable.Range(0, val+1), JsonRequestBehavior.AllowGet);
}