jquery - .NET 相当于 JQuery.param()

标签 jquery .net url asp.net-web-api query-string

我想改进我的 Web API 测试并寻找一种更好地格式化 URL 的方法。

var filter = new {
    State = new[] {"A", "C"},
    MaxAge = 60,
    POI = new { Lat = 40, Long = -130 }
};

我应该调用什么来将查询字符串格式化为 JQuery.param()函数有什么作用?

最佳答案

There您可以找到一个扩展方法,它可以帮助您将对象转换为查询字符串

public static class UrlHelpers
{
    public static string ToQueryString(this object request, string separator = ",")
    {
        if (request == null)
            throw new ArgumentNullException("request");

        // Get all properties on the object
        var properties = request.GetType().GetProperties()
            .Where(x => x.CanRead)
            .Where(x => x.GetValue(request, null) != null)
            .ToDictionary(x => x.Name, x => x.GetValue(request, null));

        // Get names for all IEnumerable properties (excl. string)
        var propertyNames = properties
            .Where(x => !(x.Value is string) && x.Value is IEnumerable)
            .Select(x => x.Key)
            .ToList();

        // Concat all IEnumerable properties into a comma separated string
        foreach (var key in propertyNames)
        {
            var valueType = properties[key].GetType();
            var valueElemType = valueType.IsGenericType
                                    ? valueType.GetGenericArguments()[0]
                                    : valueType.GetElementType();
            if (valueElemType.IsPrimitive || valueElemType == typeof (string))
            {
                var enumerable = properties[key] as IEnumerable;
                properties[key] = string.Join(separator, enumerable.Cast<object>());
            }
        }

        // Concat all key/value pairs into a string separated by ampersand
        return string.Join("&", properties
            .Select(x => string.Concat(
                Uri.EscapeDataString(x.Key), "=",
                Uri.EscapeDataString(x.Value.ToString()))));
    }
}

并将其用作string querystring = example.ToQueryString();

关于jquery - .NET 相当于 JQuery.param(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088663/

相关文章:

php - 当内部表单出现错误时,如何保持jQuery模式框打开?

javascript - 无法处理 jQuery ajax 提交的简单表单

javascript - jQuery UI 可放置类

c# - 是否可以将相同的 DLL 添加两次到 AppDomain 中,或者最好重新使用加载的 DLLC?

c# - URL 用 + 号替换空格

jquery - 上传并插入文本区域

.net - 如何在 CefSharp WPF 中保存 cookie

android - 从 URL 启动应用程序

php - 根据 PHP url 变量显示特定模式

.Net Thread vs ThreadPool vs SerialPort 通信任务