Reputation: 622
I want to pass parameters to OnGet()
method but it's not stable and everytime is different, For example:
test.com/book
test.com/book/page/word
test.com/book/page
test.com/book/page/word/...
the parameters are not stable and are created dynamically.
How can I handle this problem?
Upvotes: 2
Views: 6171
Reputation: 14472
You can handle this with the @page
directive.
There are several options based on your actual needs.
You know the structure of your URL in advance
In your .cshtml
page, you add the @page
directive, with each optional parameter followed by a question mark. Note that you can also specify constraints to specify that a particular parameter needs to be a certain type like an integer (e.g. here line
is an optional integer).
@page "/book/{pageName?}/{line:int?}/{word?}"
In your model class, you add nullable optional parameters matching the names in the @page
directive:
public void OnGet([FromRoute] string pageName= null, [FromRoute] int? line = null, [FromRoute] string word = null)
{
// TODO handle parameters
// note that line is guaranteed to be an integer
}
You don't know the exact structure of your URL
In that case, you can use a wildcard parameter, specified with a star before the parameter name:
@page "/book/{*content}"
public void OnGet([FromRoute] string content= null)
{
// TODO handle content
}
In that case, content
will contain the entire string passed after /book/
, forward slashes included, such as page/word/5/test
. You can then process it depending on your needs.
Upvotes: 7