您可以看到此示例将 Class 转换为“查询字符串”
例如,对于您拥有的课程,必须是这样的:
Name = My name
Surname = My Surname
SomeData = [
{
Name = My SD0Name,
Value = My SD0Value
},
{
Name = My SD1Name,
Value = My SD1Value
}
]
Name=My%20name&Surname=My%20Surname&SomeData[0].Name=My%20SD0Name&SomeData[0].Value=My%20SD0Value&SomeData[1].Name=My%20SD1Name&SomeData[1].Value=My%21SD0Value
那么您必须将您的网址与新文本连接起来:
var someViewModel = new ToQueryString { Name = "My name", ... };
var querystring = someViewModel.ToQueryString();
Response.Redirect("http://somedomain.com/SomeAction?redirect=" + querystring, true);
您不需要HttpUtility.UrlEncode
,因为扩展程序已经在处理这样做。
编辑@Matthew 评论。如果您有一个很大的查询字符串,您可以使用像这个列表这样的工具来压缩查询字符串,然后连接一个值:
c-compress-and-decompress-strings
压缩-解压缩-字符串-with-c-sharp
在这种情况下,您可以使用 Json 格式,已经将文本的 zip 发送到变量中。但是您需要更改然后接收此参数的操作:
Response.Redirect("http://somedomain.com/SomeAction?redirectZip=" + jsonStringZip, true);
此博客中的代码:
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()))));
}
}