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

时间:2014-09-11 11:20:31

标签: jquery ajax asp.net-mvc json jquery-ui-autocomplete

我有一个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);
    }
});

那么,一旦用户在我的视图中选择了AJAX调用并且我的GetBusinessDescription方法只过滤了处于选定状态的业务,我怎么能发送StateID的值?

1 个答案:

答案 0 :(得分:2)

在源选项中,使用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);
    }
});