无法在MVC中使用Ajax填充DropDownList

时间:2014-11-28 12:29:12

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

一切似乎都没问题,但价值显示为空 我有2个下拉列表,当我选择第一个时,我得到索引并使用ajax来填充其他下拉列表..但问题是我没有结果..循环是在ajax,不起作用..我检查了web工具firefox,结果似乎是空的,但在C#代码中,列表中有项目..

所以这是我的ajax

        $.ajax({
            url: "@Url.Action("ElectionList", "Home")",
            type: "GET",
            dataType: "json",
            data: { electionTypeId: selectedId },

        success: function (data) {


            if (data != null) {
   //HERE IS WORKING
                alert("OK");

                electionCombo.html('');
                $.each(data, function (index,item) {
     //here is not working !!! 
                    alert("hobaaa: " + index);  
                    alert("data: " + item.Text);
                    //    alert(option.ID + "  " + option.politicName);
                    //  electionCombo.append($('<option></option>').val(option.Value).html(option.Text));
                });

            }

这是我的c#代码

  [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult ElectionList(int electionTypeId)
    {


        var service = new EvoteServicesProviderClient();


        try
        {
        var electtionType = service.getAllElectionTypes().FirstOrDefault(e => e.ID == electionTypeId);

           var  res =
                service.searchElectionByType(electtionType.electionTypeName)
                    .ToList()
                    .Where(e => e.startDate >= DateTime.Now)
                    .Select(e => new SelectListItem
                    {
                        Value = e.ID.ToString(),
                        Text = e.politicName
                    });


            var list = new SelectList(res, "Value", "Text");
            return Json(list, JsonRequestBehavior.AllowGet);

         //   return Json(new { success = true, result = list },
           //      JsonRequestBehavior.AllowGet); 

        }
        catch{}

        return Json(new { success = false, message = "An error occured" }, JsonRequestBehavior.AllowGet);


    }

这是html方面

@using (Html.BeginForm("ElectionList", "Home", FormMethod.Post, new {@class = "form-horizontal", id = "electionlistform"}))
{
    @Html.LabelFor(m => m.SelectedElectionId, new {@class = "col-md-2 control-label"})
    @Html.DropDownListFor(m => m.SelectedElectionId, Model.ElectionList, new {@class = "form-control", id = "electionList"})
    @Html.ValidationMessageFor(m => m.SelectedElectionId)
}

正如我所写,列表不为空(在actionresult ElectionList中)

我缺少什么?

2 个答案:

答案 0 :(得分:2)

试试这个:

$.each(data, function () {
 //here is not working !!! 
                alert("hobaaa: " + this.Value);  
                alert("data: " + this.Text);
 });

您可以直接访问该属性,因为它是json。

<强>更新

只需返回列表服务器端:

var  res =
            service.searchElectionByType(electtionType.electionTypeName)
                .ToList()
                .Where(e => e.startDate >= DateTime.Now)
                .Select(e => new SelectListItem
                {
                    Value = e.ID.ToString(),
                    Text = e.politicName
                });


                return Json(res, JsonRequestBehavior.AllowGet);

答案 1 :(得分:1)

当我需要填写下拉列表时,我所做的与您相同,但我使用的是for循环而不是每个(也许它是相同的,但对我来说它是有效的)。顺便说一下,在你的ajax代码示例中,你没有关闭ajax函数。希望你的真实代码没关系。

   $.ajax({
            url: "@Url.Action("ElectionList", "Home")",
            type: "GET",
            dataType: "json",
            data: { electionTypeId: selectedId },

        success: function (data) {


            if (data != null) {
   //HERE IS WORKING
                alert("OK");

                electionCombo.html('');
                for (i in data) {
                    var result = data[i];
                    //  electionCombo.append($('<option></option>').val(result.Value).html(result.Text));
                }

            }
   });

顺便说一下,如果它还没有工作,你可以尝试一个ViewModel,你需要的选项

public class ViewModelExample
{
    public Int32 ValueOption { get; set; }
    public String TextOption { get; set; }
}

并在列表中使用它而不是选择列表。使用viewmodels,我在使用json获取值时没有问题。