user1283776
user1283776

Reputation: 21834

Receive query string array in ASP.NET?

This is my URI encoded query string as seen in the browser:

?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:

"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.

How do I tell my ASP.NET controller to save Request.QueryString[1] to a typed variable?

Upvotes: 2

Views: 686

Answers (2)

Du Nguyễn Phan
Du Nguyễn Phan

Reputation: 79

You may want to use 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};
    }
}

Upvotes: 1

Tarek
Tarek

Reputation: 1279

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.

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])));

Upvotes: 2

Related Questions