簡體   English   中英

無法在MVC中使用Ajax填充DropDownList

[英]Can't Filling DropDownList with Ajax in MVC

一切似乎都正常,但值顯示為空。.我有2個dropdownlist,當我選擇第一個時,我得到了索引並用ajax填充了其他dropdownlist。.但問題是我沒有結果.. ajax中的循環,沒有工作..我檢查了firefox的網絡工具,結果似乎為空,但是在C#代碼中,列表中有項目。

所以這是我的阿賈克斯

        $.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)
}

如我所寫,列表不為空(在actionresulting ElectionList中)

我缺少什么?

嘗試這個 :

$.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);

我需要填寫下拉菜單時的操作與您相同,但是我使用的是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; }
}

並在您的列表而不是selectlist中使用它。 使用viewmodel,我沒有問題可以通過json獲取值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM