Question

I'm write this function:

public static String QueryString(string queryStringKey)
{
    if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
    {
        if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
            return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
    }
    return "NAQ";
}

And i want to get just one value from querystring parameter. for example i send "page" to my function and url is: "sth.com/?page=1&page=2" and function return to me: "1,2" ; but i want first value: "1", How?

Was it helpful?

Solution

GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.

You could also use the Enumerable.First extension method:

Request.QueryString.GetValues("page").First();  

Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):

public static String QueryString(string queryStringKey)
{
    if (HttpContext.Current != null && HttpContext.Current.Request != null)
    {
        string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
        if (values != null) return values.First();
    }
    return "NAQ";
}

OTHER TIPS

A better approach would be -

public static String QueryString(string queryStringKey)
{

    if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
    {
        return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
    }
    return "NAQ";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top