【发布时间】:2014-11-05 07:45:59
【问题描述】:
我有一个 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);
}
然后,我想在我的 JS 中使用 AJAX 调用它,但我不知道如何实现它。简单地说,我想将用户选择的 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 的值发送到仅过滤处于选定状态的企业?
【问题讨论】:
标签: jquery ajax asp.net-mvc json jquery-ui-autocomplete