我需要在 .net MVC 程序中使用 jQuery-ui“自动完成”,但它不起作用。任何人都可以帮助我,我将不胜感激。
查看代码如下:
<head runat="server">
<link href="../../Content/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
</head>
<script type="text/ecmascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Product/GetProductName/",
dataType: "json",
data: { categoryID: <%: Model.Select(o => o.Category.CategoryName).Distinct().Count() > 1 ? 0 : Model.FirstOrDefault().CategoryID %> },
contentType: "application/json; charset=utf-8",
success: function(data) {
$('#productNameSearch').autocomplete({
minLength: 0,
source: Sys.Serialization.JavaScriptSerializer.deserialize(data),
focus: function(event, ui) {
$('#productNameSearch').val(ui.item.ProductName);
return false;
},
select: function(event, ui) {
$('#productNameSearch').val(ui.item.ProductName);
$('#selectedValue').text("Selected value:" + ui.item.ProductID);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
</script>
<% using (Html.BeginForm("ProductNameSearch", "Product", FormMethod.Post)) {%>
<input type="text" id="productNameSearch" name="productNameSearch" style="width:300px" />
<input type="submit" value="Go!" />
<div id="selectedValue"></div>
<%}%>
Controller 代码如下:
[HttpGet]
public ActionResult GetProductName(int? categoryID)
{
return Json(from p in pr.GetProductList() where p.CategoryID == 2 select new { ProductID = p.ProductID, ProductName = p.ProductName }, JsonRequestBehavior.AllowGet);
}
最佳答案
如果您返回的 json 数据如下所示:
[ { ProductID: 1, ProductName: "Red Hat" }, { ProductID: 2, ProductName: "Red Scarf" }]
然后自动完成功能不知道要显示什么。
它需要一个值和/或标签字段。
尝试返回与此类似的数据:
[ { value: 1, label: "Red Hat" }, { value: 2, label: "Red Scarf" }]
也许有了这个改变(我不完全确定,但你应该明白):
return Json(from p in pr.GetProductList() where p.CategoryID == 2 select new { value = p.ProductID, label = p.ProductName }, JsonRequestBehavior.AllowGet);
block 引用>The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
关于jQuery-UI 自动完成功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13756658/