【问题标题】:At.js @mention - C# Web APIAt.js @mention - C# Web API
【发布时间】:2017-03-11 22:44:26
【问题描述】:

我正在使用https://github.com/ichord/At.js 库来实现自动完成。

但是当我使用 remoteFilter 时,它会显示“未定义”下拉列表,就像他们在 https://github.com/ichord/At.js/wiki/How-to-use-remoteFilter 中所说的那样。

型号:

public class CaseHistory
{
    public int CaseHistoryId { get; set; }


    [Display(Name = "Symptom/Disease")]
    [Required(ErrorMessage = "Please enter symptom or disease")]
    public string SymptomOrDisease { get; set; }

    public string Description { get; set; }

}

API 操作代码:

   private ApplicationDbContext db = new ApplicationDbContext();

    // GET api/CaseHistories
    public IQueryable<CaseHistory> GetCaseHistories()
    {
        return db.CaseHistories;
    }

这是我在剃刀视图中的代码:

    var myUrl = 'https://localhost:44301/api/CaseHistories';

    $('#inputor').atwho({
    at: ":",
    callbacks: {
        /*
         It function is given, At.js will invoke it if local filter can not find any data
         query [String] matched query
         callback [Function] callback to render page.
        */
        remoteFilter: function(query, callback) {
            $.getJSON(myUrl, { q: query }, function (data) {
                callback(data);
            });
        }
    }
    });

【问题讨论】:

  • 请分享Api操作代码
  • @zaitsman 我已添加 Api 操作代码。

标签: javascript c# jquery at.js


【解决方案1】:

将控制器中的代码更改为:

   public dynamic GetCaseHistories()
    {
        return db.CaseHistories.Select(x => x.SymptomOrDisease).ToList();
    }

问题是你传递给回调的参数应该是字符串数组。

如果你真的想在 js 中这样做:

    var myUrl = 'https://localhost:44301/api/CaseHistories';

    $('#inputor').atwho({
    at: ":",
    callbacks: {
        /*
         It function is given, At.js will invoke it if local filter can not find any data
         query [String] matched query
         callback [Function] callback to render page.
        */
        remoteFilter: function(query, callback) {
            $.getJSON(myUrl, { q: query }, function (data) {
            var targetData = [];
                for(var i = 0;i < data.length;i++){
                        targetData.push(data[i].SymptomOrDisease);
                }
                callback(targetData);
            });
        }
    }
    });

【讨论】:

  • 有没有办法在视图中使用 jquery 来实现这一点,而无需更改控制器?
  • 查看更新后的答案。但是,这实际上效率不高,因为您实际上是从 db 中选择数据然后将其丢弃。
  • 我明白了。然后我将选择 db 选项的数据。还有一件事,当我使用 'api/CaseHistories' 作为 myUrl 时,url 变为 localhost:44301/Prescriptions/Create。这里的处方是当前视图的控制器[上面的这个视图]如何只传递 api/CaseHistories 作为 url,而不像上面的代码那样使用完整的 url?
  • 你应该能够简单地使用var myUrl = '/api/CaseHistories';,它会在用户正在查看页面的主机的根目录中请求 api
猜你喜欢
  • 2018-01-13
  • 2020-12-12
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 2017-03-17
  • 2015-04-23
相关资源
最近更新 更多