2

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);
    }
Timsen
  • 4,066
  • 10
  • 59
  • 117

1 Answers1

6

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.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • @Timsen: Sorry, you should use `ToList()` or `ToArray()` which I forgot to include at the beginning. – Oleg Sep 12 '11 at 20:23
  • Now action get called everytime i am trying to write something in the field, but my list still doesnt shows up – Timsen Sep 13 '11 at 06:33
  • @Timsen: I see some errors in your code. I have to do other things now, but if your problem will still not solve till the time, I will write you later a demo which demonstrate the usage of `autocomplete` (inclusive custom rendering with `_renderItem`) in ASP.NET MVC. – Oleg Sep 13 '11 at 09:11
  • just cant get it to work... tryed to simplyfie it, to only use name, but it didnt worked either. – Timsen Sep 13 '11 at 19:59
  • @Timsen: I modified my answer and included [the VS010 demo project](http://www.ok-soft-gmbh.com/jqGrid/jqGridDemoVS2010_withAutocomplete.zip) which can be use to "play" with the functionality. – Oleg Sep 14 '11 at 10:14
  • Works like a charm, i was missing the term part ofcourse, i should have known that, since controller just dont know what to seasrch for.. Thatnk you so much Oleg – Timsen Sep 14 '11 at 10:29
  • @Timsen: You are welcome! I make minimal modification in the code of the demo. Ij you downloaded it before you can download it one more time. – Oleg Sep 14 '11 at 10:50