MVC 5 jQuery UI 自动完成文本框,获取有关值选择的其他项目详细信息
MVC 5 jQuery UI Autocomplete textbox, get other item details on value selection
问题:
在 jQuery UI Autocomplete 文本框中(ASP.NET MVC 5 Razor 环境),
当用户选择一个值时,表单上的其他字段应该自动填写
下面是自动完成的实现。 (到目前为止有效)
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetItemCode")',
minLength: 1
});
});
</script>
现在,当用户从自动完成文本框中选择一个项目时,
表格上的其他字段应该被填充。
试图实施 jQuery Autocomplete API docs, on select
但无济于事
select: function (event, ui) {
//fill selected customer details on form
$.ajax({
cache: false,
async: false,
type: "POST",
url: "@(Url.Action("GetItemDetails", " Home"))",
data: { "id": ui.item.Id },
success: function (data) {
$("#ItemName").val(data.ItemName);
...
...
只得到错误:
- 未定义,// json未定义
- 500 内部服务器错误 // json
如前所述,自动完成功能正在运行,我正在寻找详细信息(其他表单控件 - 文本框)以自动填充从自动完成文本框中选择的值。
答案:
有效实施:
<link rel="stylesheet" href="@Url.Content("//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css")">
<script src="@Url.Content("//code.jquery.com/jquery-1.10.2.js")"></script>
<script src="@Url.Content("//code.jquery.com/ui/1.11.4/jquery-ui.js")"></script>
<script type="text/javascript">
$(function () {
$("#ItemCode").autocomplete({
source: function (request, response) {
var itemnamecodes = new Array();
$.ajax({
async: false, cache: false,
//type: "POST",
url: "@(Url.Action("GetItemCode", "Home"))",
data: { "term": request.term },
success: function (data) {
for (var i = 0; i < data.length ; i++) {
itemnamecodes[i] = { label: data[i].Value, Id: data[i].Key };
}
}
});
response(itemnamecodes);
},
select: function (event, ui) {
$.ajax({
cache: false, async: false, type: "POST",
url: "@(Url.Action("GetItemDetails", "Home"))",
data: { "id": ui.item.Id },
success: function (data) {
var item = data[0];
$("#ItemName").val(item.ItemName);
$("#ItemModel").val(item.ItemModel);
... the other details you need
action = data.Action;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Item.');
}
});
}
});
});
</script>
@using (Html.BeginForm())
{
...
@Html.EditorFor(model => model.ItemCode, ...
@Html.EditorFor(model => model.ItemName, ...
... other form elements to show details
在控制器中,
public JsonResult GetItemCode(string term)
{
// var codes = db.w_Items.Where(i => i.ItemCode.StartsWith(term)).ToList();
var result = new List<KeyValuePair<string, string>>();
var namecodes = new List<SelectListItem>();
namecodes = (from u in db.w_Items select new SelectListItem { Text = u.ItemCode, Value = u.w_ItemId.ToString() }).ToList();
foreach (var item in namecodes)
{
result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));
}
var namecodes1 = result.Where(s => s.Value.ToLower().Contains
(term.ToLower())).Select(w => w).ToList();
return Json(namecodes1, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetItemDetails(int id)
{
var codeList = db.w_Items.Where(i => i.w_ItemId == id).ToList();
var viewmodel = codeList.Select(x => new
{
Id = x.w_ItemId,
ItemName = x.ItemName,
ItemModel = x.ItemModel,
... the other details you need
});
return Json(viewmodel);
}
有两件事令人厌烦:
(此处为解决方案)
json 数据是 array 的形式,所以你需要同样对待它:
var item = data[0];
还有一件很烦人的事..现在解决:
您需要传递具有 特定 属性的视图模型作为 json 结果在 View
中处理
我就是这样做的,希望对你有帮助。
Css
enter code here.isloading1 {
background-color: #ffffff;
background-image: url("http://loadinggif.com/images/image-selection/3.gif");
background-size: 16px 16px;
background-position:right center;
background-repeat: no-repeat;
}
感谢TejSoft
控制器
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = _CustomerRepo.getCustomerDetails(prefix);
return Json(customers);
}
JS
$(function () {
$("#Customer_Name").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Controller/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
//value is the default list value in auto compleate drop down
value: item.CustomerName,
id: item.CustomerID,
CustomerAddress: item.CustomerAddress,
CustomerCity: item.CustomerCity,
CustomerPostcode: item.CustomerPostcode
};
}));
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
//TestCode
// alert("CustomerName - " + i.item.value + " PostCode - " + i.item.CustomerPostcode + " CustomerCity - " + i.item.CustomerCity + " CustomerAddress - " + i.item.CustomerAddress);
//set value for hiden field
$("#pickup_addressline2").val(i.item.CustomerAddress);
$("#CustomerCity").val(i.item.CustomerCity);
$("#CustomerID").val(i.item.ID);
$("#CustomerPostcode").val(i.item.CustomerPostcode);
},
minLength: 1,
/* Show spinner while loading data #2 */
search: function () {
$("#Customer_Name").addClass("isloading1");
},
response: function () {
$("#Customer_Name").removeClass("isloading1");
}
});
});
问题:
在 jQuery UI Autocomplete 文本框中(ASP.NET MVC 5 Razor 环境),
当用户选择一个值时,表单上的其他字段应该自动填写
下面是自动完成的实现。 (到目前为止有效)
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetItemCode")',
minLength: 1
});
});
</script>
现在,当用户从自动完成文本框中选择一个项目时, 表格上的其他字段应该被填充。
试图实施 jQuery Autocomplete API docs, on select 但无济于事
select: function (event, ui) {
//fill selected customer details on form
$.ajax({
cache: false,
async: false,
type: "POST",
url: "@(Url.Action("GetItemDetails", " Home"))",
data: { "id": ui.item.Id },
success: function (data) {
$("#ItemName").val(data.ItemName);
...
...
只得到错误:
- 未定义,// json未定义
- 500 内部服务器错误 // json
如前所述,自动完成功能正在运行,我正在寻找详细信息(其他表单控件 - 文本框)以自动填充从自动完成文本框中选择的值。
答案:
有效实施:
<link rel="stylesheet" href="@Url.Content("//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css")">
<script src="@Url.Content("//code.jquery.com/jquery-1.10.2.js")"></script>
<script src="@Url.Content("//code.jquery.com/ui/1.11.4/jquery-ui.js")"></script>
<script type="text/javascript">
$(function () {
$("#ItemCode").autocomplete({
source: function (request, response) {
var itemnamecodes = new Array();
$.ajax({
async: false, cache: false,
//type: "POST",
url: "@(Url.Action("GetItemCode", "Home"))",
data: { "term": request.term },
success: function (data) {
for (var i = 0; i < data.length ; i++) {
itemnamecodes[i] = { label: data[i].Value, Id: data[i].Key };
}
}
});
response(itemnamecodes);
},
select: function (event, ui) {
$.ajax({
cache: false, async: false, type: "POST",
url: "@(Url.Action("GetItemDetails", "Home"))",
data: { "id": ui.item.Id },
success: function (data) {
var item = data[0];
$("#ItemName").val(item.ItemName);
$("#ItemModel").val(item.ItemModel);
... the other details you need
action = data.Action;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Item.');
}
});
}
});
});
</script>
@using (Html.BeginForm())
{
...
@Html.EditorFor(model => model.ItemCode, ...
@Html.EditorFor(model => model.ItemName, ...
... other form elements to show details
在控制器中,
public JsonResult GetItemCode(string term)
{
// var codes = db.w_Items.Where(i => i.ItemCode.StartsWith(term)).ToList();
var result = new List<KeyValuePair<string, string>>();
var namecodes = new List<SelectListItem>();
namecodes = (from u in db.w_Items select new SelectListItem { Text = u.ItemCode, Value = u.w_ItemId.ToString() }).ToList();
foreach (var item in namecodes)
{
result.Add(new KeyValuePair<string, string>(item.Value.ToString(), item.Text));
}
var namecodes1 = result.Where(s => s.Value.ToLower().Contains
(term.ToLower())).Select(w => w).ToList();
return Json(namecodes1, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetItemDetails(int id)
{
var codeList = db.w_Items.Where(i => i.w_ItemId == id).ToList();
var viewmodel = codeList.Select(x => new
{
Id = x.w_ItemId,
ItemName = x.ItemName,
ItemModel = x.ItemModel,
... the other details you need
});
return Json(viewmodel);
}
有两件事令人厌烦:
(此处为解决方案)
json 数据是 array 的形式,所以你需要同样对待它:
var item = data[0];
还有一件很烦人的事..现在解决:
您需要传递具有 特定 属性的视图模型作为 json 结果在 View
中处理我就是这样做的,希望对你有帮助。
Css
enter code here.isloading1 {
background-color: #ffffff;
background-image: url("http://loadinggif.com/images/image-selection/3.gif");
background-size: 16px 16px;
background-position:right center;
background-repeat: no-repeat;
}
感谢TejSoft
控制器
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = _CustomerRepo.getCustomerDetails(prefix);
return Json(customers);
}
JS
$(function () {
$("#Customer_Name").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Controller/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
//value is the default list value in auto compleate drop down
value: item.CustomerName,
id: item.CustomerID,
CustomerAddress: item.CustomerAddress,
CustomerCity: item.CustomerCity,
CustomerPostcode: item.CustomerPostcode
};
}));
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
//TestCode
// alert("CustomerName - " + i.item.value + " PostCode - " + i.item.CustomerPostcode + " CustomerCity - " + i.item.CustomerCity + " CustomerAddress - " + i.item.CustomerAddress);
//set value for hiden field
$("#pickup_addressline2").val(i.item.CustomerAddress);
$("#CustomerCity").val(i.item.CustomerCity);
$("#CustomerID").val(i.item.ID);
$("#CustomerPostcode").val(i.item.CustomerPostcode);
},
minLength: 1,
/* Show spinner while loading data #2 */
search: function () {
$("#Customer_Name").addClass("isloading1");
},
response: function () {
$("#Customer_Name").removeClass("isloading1");
}
});
});