Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

JqGrid with autocompletion cant parse data from controller to view

Last few days i was trying to get jqgrid with autocompletion fields to work, now i can get it to work with local data, but as soon as i trying to get data from my controller data didnt get parsed.

View code:

          { name: 'EanNummer', index: 'EanNummer', width: 65, sortable: true, editable: true, edittype: 'text', editoptions: {
              dataInit:
          function (elem) {
              $(elem).autocomplete({ minLength: 0, source: '@Url.Action("GetBrands")' })
              .data("autocomplete")._renderItem = function (ul, item) {
                  return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.Id + ", " + item.Name + "</a>")
            .appendTo(ul);
              };
          } 
          }
          },

if instead of source: url i use source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] for example code works fine and shows up, so something must be wrong with my controller side code

Controller Code:

    public JsonResult GetBrands()
    {

        string vendorId = "";
        var username = "";
        var name = System.Web.HttpContext.Current.User.Identity.Name;
        var charArray = name.Split("".ToCharArray());
        username = charArray.Last();
        vendorId = service.GetVendorIdByUsername(username);

        List<String> list = new List<String>();
        var brands = service.getBrandsByVendor(vendorId);

        var s= (from brand in brands
                     select new
                     {
                         Id = brand.BrandId,
                         Name = brand.BrandName

                     }).ToList();

        return Json(s);
    }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use item.Id and item.Name on the client side you should return not the List<String>. Instead of that you should returns the list of new {Id=brand.BrandId, Name=brand.BrandName}. You should just use LINQ instead of foreach:

return Json ((from brand in brands
              select new {
                  Id = brand.BrandId,
                  Name = brand.BrandName
              }).ToList());

UPDATED: I modified for you the demo from the answer and included jQuery UI Autocomplete support in two forms. The standard rendering:

enter image description here

and the custom rendering:

enter image description here

The Autocomplete functionality works in Advanced Searching dialog in the same way like in the Searching Toolbar:

enter image description here

You can download the demo from here.

The server code of the standard autocomplete is

public JsonResult GetTitleAutocomplete (string term) {
    var context = new HaackOverflowEntities();
    return Json ((from item in context.Questions
                  where item.Title.Contains (term)
                  select item.Title).ToList(),
                 JsonRequestBehavior.AllowGet);
}

It returns array of strings in JSON format. The list of Titles are filtered by term argument which will be initialized to the string typed in the input field.

The server code of the custom autocomplete is

public JsonResult GetIds (string term) {
    var context = new HaackOverflowEntities();
    return Json ((from item in context.Questions
                  where SqlFunctions.StringConvert((decimal ?)item.Id).Contains(term) 
                  select new {
                      value = item.Id,
                      //votes = item.Votes,
                      title = item.Title
                  }).ToList (),
                 JsonRequestBehavior.AllowGet);
}

It uses SqlFunctions.StringConvert to be able to use LIKE in comparing of the integers. Moreover it returns the list of objects having value the title property. If you would return objects having value the lable properties the values from the lable properties will be displayed in the Autocomplete context menu and the corresponding value property will be inserted in the input field. We use custom title property instead.

The code of the client side is

searchoptions: {
    dataInit: function (elem) {
        $(elem).autocomplete({ source: '<%= Url.Action("GetTitleAutocomplete") %>' });
    }
}

for the standard rendering and

searchoptions: {
    sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
    dataInit: function (elem) {
        // it demonstrates custom item rendering
        $(elem).autocomplete({ source: '<%= Url.Action("GetIds") %>' })
            .data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a><span style='display:inline-block;width:60px;'><b>" +
                        item.value + "</b></span>" + item.title + "</a>")
                    .appendTo(ul);
            };
    }
}

for the custom rendering.

Additionally I use some CSS settings:

.ui-autocomplete {
    /* for IE6 which not support max-height it can be width: 350px; */
    max-height: 300px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
    /* add padding to account for vertical scrollbar */
    padding-right: 20px;
}
/*.ui-autocomplete.ui-menu { opacity: 0.9; }*/
.ui-autocomplete.ui-menu .ui-menu-item { font-size: 0.75em; }
.ui-autocomplete.ui-menu a.ui-state-hover { border-color: Tomato }
.ui-resizable-handle {
    z-index: inherit !important;
}

You can uncomment .ui-autocomplete.ui-menu { opacity: 0.9; } setting if you want to have some small opacity effect in the autocomplete context menu.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...