如何获取DropDownList的值并将其传递到MVC5中的AJAX调用中



我有一个MVC5应用程序,我有一种定义如下的模型:

public class Request
{
    ...
    [ForeignKey("State")]
    public int StateID { get; set; }
    public virtual State State { get; set; }
    public string ServiceName { get; set; }
}

我的状态模型定义如下:

public class State
{
    public int StateID { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
}

在我看来,我正在工作,我有这样的东西:

        <div class="form-group">
            @Html.LabelFor(model => model.StateID, "State", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("StateID", null, "Please select a state", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.StateID, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.ServiceName, "Service", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ServiceName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ServiceName, "", new { @class = "text-danger" })
            </div>
        </div>

重点是,我想在ServiceName的输入框中插入自动完成,为此我编写了JsonResult方法,定义如下:

    public JsonResult GetBusinessDesriptions(int state, string term)
    {
        var results = db.Users.OfType<Business>().Where(b => b.StateID == state && (term == null || b.Description.ToLower().Contains(term.ToLower()))).Select(x => new { id = x.StateID, value = x.Description }).Take(5).ToList();
        return Json(results, JsonRequestBehavior.AllowGet);
    }

然后,我想用AJAX在我的JS中调用它,但我不知道如何实现。简单地说,我想把用户选择的StateID传递给AJAX调用和GetBusinessDescription方法的调用。

我有这样的东西,但它不起作用,因为我不知道如何传递视图中选择的StateID,所以它只读取处于所选状态的业务。

$("#Service-Name").autocomplete({
    source: "/Home/GetBusinessDesriptions",
    minLength: 2,
    select: function (event, ui) {
        $("#Service-Name").val(ui.item.value);
        $("#Service-Name").text(ui.item.value);
    }
});

那么,一旦用户在我的视图中选择,我如何将StateID的值发送到AJAX调用和我的GetBusinessDescription方法,以便只过滤处于所选状态的业务?

例如,在源代码选项中使用ajax并传递额外的参数。这里StateId是状态下拉列表的id。

$("#Service-Name").autocomplete({
    source: function( request, response ) {
        $.ajax({
          url: "/Home/GetBusinessDesriptions",
          dataType: "jsonp",
          data: {
            state:$("#StateID").val(),
            term: request.term
          },
          success: function( data ) {
            response( data );
          }
        });
      },
    minLength: 2,
    select: function (event, ui) {
        $("#Service-Name").val(ui.item.value);
        $("#Service-Name").text(ui.item.value);
    }
});

最新更新