22

I'm learning ASP.NET and stumbled upon this method declaration:

public IQueryable<Product> GetProducts([QueryString("id")] int? categoryId) {.....} 

The tutorial said categoryId will be equal to query string "id" (From URL, like &id=5) but the question is what is [QueryString("id")] syntax called? Is this usable outside ASP.NET and what will the application of this be?

1 Answer 1

21

That's applying the QueryStringAttribute attribute to the parameter categoryId. It's just an attribute, just like the ones you're probably more used to seeing on methods or classes, like this:

[STAThread] static void Main() { } 

In this case, presumably some part of the framework (I'm not an ASP.NET developer, so I can't point out exactly what) is using reflection to find all the methods, find any QueryStringAttribute values applied to the parameters, and then matching the names within those attributes with the names in the query string, then extracting the matching values to pass into the method call (again using reflection).

Sign up to request clarification or add additional context in comments.

3 Comments

By "attribute" did you mean this : msdn.microsoft.com/en-us/library/z0w1kczw(v=vs.80).aspx The attribute is used to describe data? AFAIK attribute is just a metadata how can this turned into real value and apply to categoryId?
@Sargon: It's metadata, yes - it's applied to the parameter itself... and ASP.NET is able to use that metadata to work out how to call GetProducts automatically. Will edit the answer to mention that.
Thanks for answer about reflection. For anyone interested to write your own attribute & reflection technique here is the page I just read : msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.