如何在json数组中获取下拉选择的值

时间:2016-05-13 12:20:51

标签: jquery json asp.net-mvc razor html.dropdownlistfor

我尝试了5种不同的方法来获取所选的下拉值,但都失败了。

// JourneyType: $("#JourneyType").find("option:selected").text(),
// JourneyType: $("#JourneyType :selected").text(),
//  JourneyType: $('#JourneyType option:selected').text(),
//   JourneyType: $("[id='JourneyType'] :selected"),

这个旅程类型对象在一个名为(sof)的json数组中,我想设置所选的下拉值。带有ajax函数的json数组是这样的:

             <script>
                $(document).ready(function () {                 
                    $("#btnPost").click(function () {
                     var sof = {
                            EndUserIp: "192.168.10.10",
                            TokenId: $("#pageInitCounter").val(),
                            AdultCount: $("#AdultCount").val(),
                            ChildCount: $("#ChildCount").val(),
                            JourneyType: $("#JourneyType :selected").text(),                                          
                        }
                        $.ajax(
                            {
                                url: "/api/Flight/SearchFlight",
                                type: "Post",
                                contentType: "application/json",
                                data: JSON.stringify(sof),
                                success: function (result) {
                                    alert(result);
                                }
                            });        
                    });
                });
        </script>

我想从中获取所选文本值的简单下拉列表:

 <div class="form-group">
                        <label class="control-label col-md-2" for="DepartmentID">Journey Type</label>
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.JourneyType, Model.JourneyList)
                            @Html.ValidationMessageFor(model => model.JourneyType, "", new { @class = "text-danger" })
                        </div>
                    </div>

这些下拉值的模型就是这样的:

   public enum JourneyType
{
    OneWay, Return, MultiStop, AdvanceSearch, SpecialReturn
}

public class SearchForFlight
{
    public SearchForFlight()
    {
        JourneyList = new List<SelectListItem>();
    }
    public string EndUserIp { get; set; }
    public string TokenId { get; set; }

    public IEnumerable<SelectListItem> JourneyList { get; set; }

    public Enum JourneyType { get; set; }
}

我正在使用这样的Web api Controller动作方法,但每次我在sof对象的JourneyType中看到null:

  public async Task<HttpResponseMessage> SearchFlight([FromBody]SearchForFlight sof)
     {
 // implementation goew here
      }

2 个答案:

答案 0 :(得分:0)

var text = $("#JourneyType").text();

答案 1 :(得分:0)

为您的id

添加html dropdownlist
@Html.DropDownListFor(model => model.JourneyType, Model.JourneyList, new {id = "JourneyType"} )