我想将Filters
对象以及其他内容作为查询参数传递到网址中,例如:
{
"clientId": 2,
"date": "2017-01-01",
"filters": {
"days": { "monday", "tuesday", "wednesday" },
"months": { "january", "february" }
}
但是我不知道这个例子中的filters
这样的对象如何被查询字符串参数传入。我知道你通常会有类似的东西:
https://localhost/path?clientId=2&date=2017-01-01&filters= ?????
谢谢!
答案 0 :(得分:2)
如果您的数据很复杂而不是作为查询字符串参数发送,则可能更好。但无论如何,如果你想发送查询字符串,你可以执行以下操作:
对于跟随对象(转换为字符串和删除的空格):
{
"clientId": 2,
"date": "2017-01-01",
"filters": {
"days": { "monday", "tuesday", "wednesday" },
"months": { "january", "february" }
}
我创建了通过网络发送安全的编码文本:
%7B%0A%22clientId%22%3A%202%2C%0A%22date%22%3A%20%222017-01-01%22%2C%0A%22filters%22%3A%20%7B%0A%22days%22%3A%20%7B%20%22monday%22%2C%20%22tuesday%22%2C%20%22wednesday%22%20%7D%2C%0A%22months%22%3A%20%7B%20%22january%22%2C%20%22february%22%20%7D%0A%7D
在你的情况下,它将是:
https://localhost/path?clientId=2&date=2017-01-01&filters=%7B%0A%22clientId%22%3A%202%2C%0A%22date%22%3A%20%222017-01-01%22%2C%0A%22filters%22%3A%20%7B%0A%22days%22%3A%20%7B%20%22monday%22%2C%20%22tuesday%22%2C%20%22wednesday%22%20%7D%2C%0A%22months%22%3A%20%7B%20%22january%22%2C%20%22february%22%20%7D%0A%7D
您可以使用meyerweb.com来测试编码/解码,但在C#中,您可以研究可以在您的情况下使用的HttpUtility.UrlEncode()方法。
答案 1 :(得分:0)
如果你真的想在查询字符串中传递参数,这是一个使用ASP.NET MVC的例子。
创建路线:
routes.MapRoute(
name: "Custom",
url: "{controller}/{action}/{clientId}/{date}/{filtersDay}/{filtersMonth}",
defaults: new { controller = "Home", action = "CustomQueryString" }
);
您可以重复一个项目,Model Binding将创建一个字符串数组:
http://localhost/Home/CustomQueryString?clientId=1&date=2017-01-01&filtersDay=Friday&filtersDay=Monday&filtersMonth=April&filtersMonth=June
答案 2 :(得分:0)
我有一个ToDictionary扩展方法,它将对象转换为查询字符串,您可以通过RouteValues传递它,我传递了Model.SearchCriteria,它是下面示例中的复杂对象:
<a href='@Url.Action("ExportAll",
new RouteValueDictionary(Model.SearchCriteria))'>Export All</a>
ToDictionary是一种扩展方法:
public static class ToDictionaryExtensionMethod
{
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
}
不幸的是,以下代码不起作用:
@Html.ActionLink("Export All", "ExportAll",
new RouteValueDictionary(Model.SearchCriteria.ToDictionary()),
new { @class = "btn btn-default" })
这是因为此版本的ActionLink接受路由值作为对象,而不是RouteValueDictionary(在MVC 5中)。因此,要使其正常工作,我还必须将Html属性转换为字典,并使用正确的Html.ActionLink重载:
@Html.ActionLink("Export All", "ExportAll",
new RouteValueDictionary(Model.SearchCriteria.ToDictionary()),
new Dictionary<string,object>{{"class","btn btn-default"}})