2

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?

3
  • What do you mean by ASP.NET ? You mean ASP.NET MVC ? Or Web Api ? Or ASP.NET Core ? These are 3 different things.
    – Fabjan
    Commented May 15, 2018 at 15:22
  • What is the %5B%5D in your URI encoded query string? Could it be that the name is wrong?
    – user5441558
    Commented May 15, 2018 at 15:24
  • @Fabjan ASP.NET MVC Commented May 15, 2018 at 15:25

2 Answers 2

2

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])));
2
  • 1
    Your controller action won't even compile. Optional parameters must appear after all required parameters.
    – penleychan
    Commented May 15, 2018 at 15:41
  • True, I just coped the thing quickly, I'll make the change. Thanks
    – Tarek
    Commented May 15, 2018 at 16:00
1

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};
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.