MVC 5 jQuery UI自动填充文本框,获取有关值选择的其他项目详细信息

时间:2016-06-25 12:05:43

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

问题:
jQuery UI Autocomplete文本框(ASP.NET MVC 5 Razor环境)中, 当用户选择一个值时,表单上的其他字段应自动填充

下面是AutoComplete实现。 (到目前为止它有效)

<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);
               ...
               ...

只得到错误:

  1. undefined,// json undefined
  2. 500内部服务器错误// json
  3. As Said说,自动完成工作正常,我正在寻找自动填充自动填充文本框中的值选择的详细信息(其他表单控件 - 文本框)。

2 个答案:

答案 0 :(得分:2)

答案:

工作实施:

<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];

另一个非常令人讨厌的事情..解决方案现在:

您需要将具有特定属性的viewmodel作为json结果传递,以便在View中处理

答案 1 :(得分:0)

我这样做是希望它有所帮助。

的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");
    }


});
});