【问题标题】:How to bind JSON data to dropdownlist in Asp.net MVC using jQuery如何使用 jQuery 将 JSON 数据绑定到 Asp.net MVC 中的下拉列表
【发布时间】:2014-04-08 06:03:18
【问题描述】:

我正在尝试将 JSON 数据绑定到下拉列表

我的场景是我想获取数据并绑定到动态下拉列表,

在单独的类中,我使用 linq 来获取类似的数据

    public SelectList getProjects()
    {
        IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
        return new SelectList(projectslist, "Value", "Text", PROJ_ID);
    }

在控制器中:

ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });

在视图中:

    @for (int i = 0; i <2; i++)
    {                                    {
   @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue" })
    }

现在,如果我们有三个下拉列表,我正在尝试,我们在第一个下拉列表中选择一个列表项不应显示在第二个下拉列表中,并且在第三个下拉列表中不应显示我之前选择的两个列表项书面脚本如:

     <script>
    $(document).ready(function () {
        $('.ddlProjectvalue').change(function () {
            debugger;
            var selectedValue = $(this).val();
            if (selectedValue != null && selectedValue != '') {
                debugger;
                $.ajax({

                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: "/Employer/GetDDLData?selectedValue="+selectedValue,
                    data: "{}",
                    dataType: "Json",
                    success: function (data) {

                        // first remove the current options if any
                        $('.ddlProjectvalue').find('option').remove();

                        // next iterate thru your object adding each option to the drop down\    
                        $(data).each(function (index, item) { // GETTING ERROR HERE
                            debugger;

                            $('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
                        });
                    },
                    error: function ajaxError(response) {
                    alert(response.status + ' ' + response.statusText);
                }
            });
        }
      });
    });
   </script>

我正在从控制器返回 JSON 数据:

    public ActionResult GetDDLData(string selectedValue)
    {
        int projectid = Convert.ToInt32(selectedValue);

        IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
        var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

我试过了,但是遇到类似的错误

      "Syntax error, Unrecognized Expression"

我在哪里做错了,请任何人帮助我。

【问题讨论】:

    标签: c# jquery asp.net-mvc json


    【解决方案1】:

    这对你有帮助:

    $.ajax({
                url: "@Url.Action("GetDDLData","Employer")",
                data: {selectedValue:selectedValue},
                dataType: "json",
                type: "GET",
                error: function () {
                    alert(" An error occurred.");
                },
                success: function (data) {
                    var optionhtml1 = '<option value="' +
                     0 + '">' + "--Select State--" + '</option>';
                    $(".ddlProjectvalue").append(optionhtml1);
    
                    $.each(data, function (i) {
    
                        var optionhtml = '<option value="' +
                    data[i].Value + '">' +data[i].Text + '</option>';
                        $(".ddlProjectvalue").append(optionhtml);
                    });
                }
            });
    

    【讨论】:

    • 谢谢它工作正常,但小问题,因为它是动态 ddl,它影响三个下拉列表,它不应该那样!如果我们选择第一个 ddl 不应该动态显示在第二个 ddl 中,反之亦然,对于总下拉列表,有什么想法吗?请帮助我。
    • 您应该为每个下拉列表提供 ID
    • 我怎么能,如果我们有超过三个或四个 ddls,我们可以为所有人传递 id 并将我们的解决方案应用于所有 ddls 吗?或者这个问题有其他解决方案吗?
    • 让我们试试吧 @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- 选择一个项目 --", new { @class= "ddlProjectvalue",@id="dropdown_"+i })
    • 你可以使用 $(this) 代替类名
    【解决方案2】:
    //Controller Code
    
    public ActionResult getAccount()
             {
                 var result = new SelectList(db.Partymsts, "Account", "Account");
                 return Json(result, JsonRequestBehavior.AllowGet);
             }
    
    // js code
    
     $.ajax({
                    type: "POST",
                    url: "/NewMaster/getAccount",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
    
                    success: function (data) {
                    var optionhtml1 = '<option value="' +
                     0 + '">' + "--Select State--" + '</option>';
                    $(".cs3").append(optionhtml1);
    
                    $.each(data, function (i) {
    
                        var optionhtml = '<option value="' +
                    data[i].Value + '">' +data[i].Text + '</option>';
                        $(".cs3").append(optionhtml);
                    });
                }
                });
    
    
    // html code
    
    
    <select id="cs3" name="cs3"   class="cs3 form-control input-small"> </select>
    
    
    
    
    its working !!
    

    【讨论】:

    • 这是得到空结果的解决方案。在下拉列表绑定中。希望对您有所帮助。
    【解决方案3】:

    如果您的 json 正确,则以下内容将起作用。将代码放入您的 ajax 成功

    success:function(data){
     $('.ddlProjectvalue').empty();
     $.each(data,function (index, item) { 
        $('.ddlProjectvalue').append$('<option>', {
                                    value: item.Value,
                                    text: item.Text
                                }, '<option/>')
                                }
                            );
       }
    

    【讨论】:

    • 不,得到 Empty 结果,无论如何感谢您的解决方案,我有不同的方法。
    • 答案已更新。如果您的 json 正确,它必须有效。如果有错误,请告诉我们。
    • 不,结果为 EMpty
    • 拜托,你能显示返回的Json吗?以便其他人可以从中获得帮助。
    • 你得到的 ID 和 Name 为 json,然后使用。值:item.ID,文本:item.Name
    【解决方案4】:

    我们已经这样做了

    Dropdown.append($('&lt;option&gt;&lt;/option&gt;').val(item.col1).text(item.col2));

    【讨论】:

      【解决方案5】:
      function GetDropDownData(stateid) {
              $.ajax({
                  type: 'GET',
                  url: '@Url.Action("getdist","Home")',
                  data: {stateid:stateid},
                  dataType: 'json',
                  success: function(data)
                  {
                      $("#districtId").empty();
                      $("#districtId").append('<option value="">--Select--</option>');
                      $.each(data, function (id, result) {
                              $("#districtId").append('<option value"'+result.Value+'">'+result.Text+'</option>');
                          });
                      },
                      failure: function () {
                          $("#districtId").empty();
                          $("#districtId").append('<option value="">--Select--</option>');
                      }
                  });
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多