简体   繁体   English

在ASP.NET中接收查询字符串数组?

[英]Receive query string array in ASP.NET?

This is my URI encoded query string as seen in the browser: 这是在浏览器中看到的我的URI编码查询字符串:

?itemsOnly=true&addedArticles%5B%5D=202&addedArticles%5B%5D=011&addedArticles%5B%5D=280&addedArticles%5B%5D=208&addedArticles%5B%5D=020

This is the relevant part of my query string as seen in the Request.QueryString[1] property in ASP.NET: 这是查询字符串的相关部分,如ASP.NET的Request.QueryString [1]属性所示:

"202,011,280,208,020"

Even though the query string is on the request, my controller ignores it. 即使查询字符串位于请求中,我的控制器也会忽略它。

I have tried the following 我尝试了以下

public ActionResult ActionName(bool itemsOnly = false, string addedArticles = "")

public ActionResult ActionName(bool itemsOnly = false, string[] addedArticles = null)

public ActionResult ActionName(bool itemsOnly = false, IEnumerable<string> addedArticles = null)

But in each case addedArticles has been empty. 但是在每种情况下,additionalArticles都是空的。

How do I tell my ASP.NET controller to save Request.QueryString[1] to a typed variable? 如何告诉我的ASP.NET控制器将Request.QueryString [1]保存到类型变量中?

Your controller action should be 您的控制器动作应为

public ActionResult ActionName(string[] addedArticles, bool itemsOnly = false)

and you could send to it a query string like 您可以向其发送查询字符串,例如

?addedArticles=[X]&addedArticles=[X2]&addedArticles=[X3]

Where [X], [X2], [X3]... are your strings. 其中[X],[X2],[X3] ...是您的字符串。

You could try and use this to encode your query string 您可以尝试使用它来编码您的查询字符串

public static string ToQueryString(this NameValueCollection self)
            => string.Join("&", self.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(self[a])));

You may want to use ModelBinder 您可能要使用ModelBinder

public ActionResult ActionName (CustomRequest request) {

}

[ModelBinder(typeof(CustomModelBinder))]
public class CustomRequest
{
    public bool itemOnly;
    public string[] addedArticles;
}

public class CustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.RequestContext.HttpContext.Request;
        var itemOnly =bool.Parse( request.QueryString["itemOnly"]);
        var addedArticles = request.QueryString["addedArticles"].Split(',');

        return new CustomRequest(){itemOnly=itemOnly,addedArticles= addedArticles};
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM