具有自动完成功能的 JqGrid 无法将数据从控制器解析到视图 [英] JqGrid with autocompletion cant parse data from controller to view

查看:12
本文介绍了具有自动完成功能的 JqGrid 无法将数据从控制器解析到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近几天我试图让带有自动完成字段的 jqgrid 工作,现在我可以让它与本地数据一起工作,但是一旦我试图从我的控制器中获取数据,数据就没有被解析.

查看代码:

 { name: 'EanNummer', index: 'EanNummer', width: 65, sortable: true, editable: true, edittype: 'text', editoptions: {数据初始化:函数(元素){$(elem).autocomplete({ minLength: 0, source: '@Url.Action("GetBrands")' }).data("自动完成")._renderItem = function (ul, item) {return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.Id + ", " + item.Name + "</a>").appendTo(ul);};}}},

如果不是 source: url 我使用 source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] 例如代码工作正常并显示,所以我的控制器端代码一定有问题

控制器代码:

 public JsonResult GetBrands(){字符串 vendorId = "";var 用户名 = "";var name = System.Web.HttpContext.Current.User.Identity.Name;var charArray = name.Split("\".ToCharArray());用户名 = charArray.Last();vendorId = service.GetVendorIdByUsername(用户名);列表<字符串>列表=新列表<字符串>();var 品牌 = service.getBrandsByVendor(vendorId);var s=(来自品牌中的品牌选择新的{Id = 品牌.BrandId,名称 = 品牌.品牌名称}).ToList();返回 Json(s);}

解决方案

如果你在客户端使用 item.Iditem.Name 你不应该返回列表<字符串>.相反,您应该返回 new {Id=brand.BrandId, Name=brand.BrandName} 的列表.您应该只使用 LINQ 而不是 foreach:

return Json ((from brand inbrands选择新的{Id = 品牌.BrandId,名称 = 品牌.品牌名称}).ToList());

更新:我为您修改了来自 对话框中工作与 下载演示.

标准自动完成的服务器代码是

public JsonResult GetTitleAutocomplete (string term) {var context = new HaackOverflowEntities();return Json ((来自上下文中的项目.问题其中 item.Title.Contains (term)选择 item.Title).ToList(),JsonRequestBehavior.AllowGet);}

它返回 JSON 格式的字符串数组.标题列表由 term 参数过滤,该参数将初始化为输入字段中键入的字符串.

自定义自动完成的服务器代码是

public JsonResult GetIds (string term) {var context = new HaackOverflowEntities();return Json ((来自上下文中的项目.问题其中 SqlFunctions.StringConvert((decimal ?)item.Id).Contains(term)选择新的{值 = item.Id,//votes = item.Votes,标题 = 项目.标题}).ToList(),JsonRequestBehavior.AllowGet);}

它使用 SqlFunctions.StringConvert 可以使用 LIKE 比较整数.此外,它返回具有 valuetitle 属性的对象列表.如果您要返回具有 valuelable 属性的对象,则来自 lable 属性的值将显示在自动完成上下文菜单和相应的 value 属性将被插入到输入字段中.我们改用自定义 title 属性.

客户端的代码是

搜索选项:{数据初始化:函数(元素){$(elem).autocomplete({ source: '<%= Url.Action("GetTitleAutocomplete") %>' });}}

用于标准渲染和

搜索选项:{sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],数据初始化:函数(元素){//它演示了自定义项目渲染$(elem).autocomplete({ source: '<%= Url.Action("GetIds") %>' }).data("自动完成")._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);};}}

用于自定义渲染.

另外我使用了一些 CSS 设置:

.ui-autocomplete {/* 对于不支持最大高度的 IE6,它可以是宽度:350px;*/最大高度:300px;溢出-y:自动;/* 防止水平滚动条 */溢出-x:隐藏;/* 为垂直滚动条添加填充 */padding-right: 20px;}/*.ui-autocomplete.ui-menu { 不透明度:0.9;}*/.ui-autocomplete.ui-menu .ui-menu-item { 字体大小:0.75em;}.ui-autocomplete.ui-menu a.ui-state-hover { 边框颜色:番茄 }.ui-resizable-handle {z-index:继承!重要;}

您可以取消注释 .ui-autocomplete.ui-menu { opacity: 0.9;} 设置,如果你想有一些小的自动完成上下文菜单中的不透明度效果.

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

解决方案

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:

and the custom rendering:

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

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.

这篇关于具有自动完成功能的 JqGrid 无法将数据从控制器解析到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆