mvc4:级联下拉列表

时间:2013-03-27 17:12:08

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

我似乎无法理解ajax和json

我想做一个级联下拉菜单,我正在尝试将数据发送到div开始。 这是脚本

<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>
<script>

    $(function () {
        $('#funtiontype').change(function () {
            var selectedValue = $(this).val();

            $.ajax(
                {
                  // url: $(this).data('url'),
                  // source: "/EmployeeReps/GetDescription",
                url: "~/EmployeeReps/GetDescription",
                type: 'GET',
                cache: false,
                data: {value: selectedValue },
                success: function (result) {
                      $('#description').html(result.employeelist);
                     }
                });

            });

        });

</script>

和控制器

[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetDescription(string value)
        {

            //get the data from DB
            var employeelist =(from s in db.tble_employeeReps where s.em_function==value 
                             select s);


            return Json(employeelist.ToList(), JsonRequestBehavior.AllowGet);
        }

HTML     @using(Html.BeginForm()){

    <fieldset>

        <div class="editor-label">Function*</div>
        <div class="editor-field">

          <select id = "funtiontype">
               <option value = "">Please Select</option>
               <option value = "Finance">Finance</option>
               <option value = "Non-Finance">Non-Finance</option>
          </select>
        </div>

        <p></p>
        <p>
            <input type="submit" value="Vote" />
        </p>
    </fieldset>
    <div id="description"></div>
}

但我很难获得任何数据。请任何人都可以帮忙

非常感谢提前 碎甲弹

1 个答案:

答案 0 :(得分:0)

控制器中的这一行:

        return Json(employeelist.ToList(), JsonRequestBehavior.AllowGet);

正在将您的员工列表更改为JSON字符串。该字符串是一个对象数组。

在你的ajax电话中:

        $.ajax(
            {
              // url: $(this).data('url'),
              // source: "/EmployeeReps/GetDescription",
            url: "~/EmployeeReps/GetDescription",
            type: 'GET',
            cache: false,
            data: {value: selectedValue },
            success: function (result) {
                  $('#description').html(result.employeelist);
                 }
            });

        });

result是相同的对象数组。 result将没有名为employeelist的属性。它实际上是一系列员工。

您需要循环该阵列并创建HTML以显示员工:

        $.ajax({
            url: "~/EmployeeReps/GetDescription",
            type: 'GET',
            cache: false,
            data: {value: selectedValue },
            success: function (result) {
                var employeeHTML = "";
                for(count = 0; count < result.length; count++) {
                    employeeHTML += "<p>" + result[count].EmployeeName + "</p>"; //your fields here
                }
                $('#description').html(employeeHTML);
            });
        });