如何从JSON返回更新我的下拉列表

How to update my dropdown list from JSON return?

本文关键字:更新 我的 下拉列表 返回 JSON      更新时间:2023-09-26

我的视图中有一个下拉列表:

<label><span class="hide">Type</span>@Html.DropDownListFor(m => m.FromValue, new SelectList(Model.FromType), new { id = "RSFromType"})</label>

这是我认为的模型:

public List<WebAMT.Layer.Models.Types.SearchFilterType> FromType { get; set; }

以下是一个列表:

public enum SearchFilterType : int
{
      All = 0,
      PreferredEntity = 1,
      ActualEntity = 2,
      CityState = 3
}

模型在我的控制器中设置:

vm.FromType = SearchLogic.GetOriginList(true);

如果为true(默认值),此下拉列表将显示All、PreferredEntity、ActualEntity和CityState。

我需要在选择单选按钮时更改这些值:

<label>@Html.RadioButtonFor(m => m.ReservationArea, false, new { id = "RSMyReservationArea" }) My Reservation Area</label>
<label>@Html.RadioButtonFor(m => m.ReservationArea, true, new { id = "RSAllReservationArea" }) All Reservation Areas</label>

因此,当选择第一个按钮时,我需要列表来显示所有四个选项,但当选择第二个时,我只需要它来显示all和CityState。

我已经为此创建了一些JQuery:

$(function () {
     $('#RSMyReservationArea').click(function () {
          UpdateReservationSearchArea(true);
     });
     $('#RSAllReservationArea').click(function () {
          UpdateReservationSearchArea(false);
     });
});
function UpdateReservationSearchArea(area) {
     $.ajax({
            type: "GET",
            async: false,
            url: "@Url.Action("UpdateReservationArea", "Search")",
            data: { MyResArea: area },
        cache: false,
        dataType: "html",
        failure: function () {
            alert(" An error occurred.");
        },
        success: function(result) {
            UpdateToAndFromTypes(result);
        }
    });
}

这导致了我的控制器:

[HttpGet]
public JsonResult UpdateReservationArea(ReservationSearchVM vm, bool myResArea)
{
       List<WebAMT.Layer.Models.Types.SearchFilterType> originList = new List<Layer.Models.Types.SearchFilterType>();
       originList = SearchLogic.GetOriginList(myResArea);
       return Json(new { originList }, JsonRequestBehavior.AllowGet);
}

这就是我遇到的问题。我有这个JQuery来处理返回,我不知道如何根据JSon返回的内容更新FromType的下拉列表,因为我所做的似乎都不起作用。所以我有一个控制台日志并检查了结果,true和false都返回originList{0,1,2,3}或originList{0,1,2,3}:

function UpdateToAndFromTypes(result) {
        $("#RSFromType").empty();
        console.log(result);
};

我需要在最后一个脚本中包含什么来更新dropdown list的内容。

假设您的result位于正确的json可枚举对象中。

   function UpdateToAndFromTypes(result) {
    $("#FromValue").empty();
       $.each(result, function(key, value) {   
         $('#FromValue')
             .append($("<option></option>")
             .attr("value",key)
             .text(value)); 
       });    
    };

由于标记已经呈现,您可以继续并替换选择标记。

function UpdateToAndFromTypes(result) 
{
        $("#RSFromType").empty();
        var selectContainer;
        for(var i=0; i < result.originList.length;i++)
        {
         selectContainer += "<option>" + result.originList[i] + "</option>";
        } 
        $("#RSFromType").html(selectContainer);
};