【问题标题】:Web API MVC get query parameter from ng-table?Web API MVC 从 ng-table 获取查询参数?
【发布时间】:2015-12-07 14:08:52
【问题描述】:

我一直在尝试让 ng-table(angular 指令) 与 web api (ASP.NET MVC) 一起工作。我可以加载和分页数据,但排序或过滤不起作用。

奇怪的是,排序或过滤在 URL 中会如下所示:

http://localhost:46278/api/rating?count=10&filter%5Brating.name%5D=fs&page=1&sorting%5Brating.description%5D=asc

如果你要“格式化”它,它会是这样的:

过滤器[rating.name] = fs
排序[rating.description] = asc

我试图用字符串数组或字典(KeyValuePair)来获取它们

但我无法获取值。所以我永远无法过滤或排序数据。

希望大家多多指教!感谢您的帮助!

【问题讨论】:

    标签: javascript asp.net angularjs asp.net-web-api2 ngtable


    【解决方案1】:

    我写了一个帮助类来处理这个问题。 URL 的格式不是 WebAPI 所期望的,因此无法让 ModelBinder 自动解析它。

    从您的控制器中,调用帮助程序并提供整个 URL:

    // Parse sortings
    var sortings = TableHelpers.ParseSortings(Request.RequestUri).ToList();
    // Parse filters
    var filters = TableHelpers.ParseFilters(Request.RequestUri).ToList();
    

    还有辅助类

    public static class TableHelpers
    {
        public static IEnumerable<TableSorting> ParseSortings(Uri requestUri)
        {
            var regex = new Regex("sorting%5B(.+?)%5D=(asc|desc)");
            var matches = regex.Matches(requestUri.AbsoluteUri);
            return from Match match in matches
                select new TableSorting {Field = match.Groups[1].Value, Order = match.Groups[2].Value};
        }
    
        public static IEnumerable<TableFilter> ParseFilters(Uri requestUri)
        {
            var regex = new Regex("filter%5B(.+?)%5D=(.+?)(?:&|\\z)");
            var matches = regex.Matches(requestUri.AbsoluteUri);
            return from Match match in matches
                select new TableFilter {Field = match.Groups[1].Value, Value = match.Groups[2].Value};
        }
    }
    
    public class TableSorting
    {
        public string Field { get; set; }
        public string Order { get; set; }
    }
    
    public class TableFilter
    {
        public string Field { get; set; }
        public string Value { get; set; }
    }
    

    【讨论】:

    • 这个帮助类是专门为 ngTable 设计的吗?
    • 是的,正则表达式用于解析 ngTable 生成的 URL
    • 好的,谢谢,有时间我会试试的。但乍一看它看起来不错:) 如果它有效,我会接受你的回答!
    【解决方案2】:

    你问的是指令语法还是你的 api?

    在 ng-table 指令中,插入&lt;td&gt; 标签sorting 或/和filtering attrs,如:

    <td width="10%" data-title="'NUM'|translate" filter="{ 'num': 'text' }" sortable="'num'"><span>{{item.num}}</span></td>
    

    【讨论】:

    • 我已经开始工作了 :) 我需要知道如何在使用服务器端数组时读取 Web API 控制器中的查询字符串参数?
    猜你喜欢
    • 2015-10-23
    • 2021-05-24
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多