Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for binding query parameters in Razor Pages

In Razor Pages, it is quite convenient that if you were to call, for example,

http://localhost/foo?bar=42

In the corresponding model, the bar key is automatically accessible in the OnGet constructor

public IActionResult OnGet(int bar)
{
    System.Console.WriteLine($"bar is {bar}");
}

But what if the query parameter is poo?

http://localhost/foo?poo=42

then in the model, bar does not get the value 42.

So simple enough, get the variables to match the query parameter key. But what if the key is hyphenated?

http://localhost/foo?foo-bar=42

foo-bar is definitely not an acceptable variable name. How do I access this query parameter? What are the rules here?

In my specific case, I don't really have a choice but to receive these hyphenated query string parameters. Also, I'm on .net core 2.2.

like image 420
Dillon Chan Avatar asked Dec 03 '22 09:12

Dillon Chan


2 Answers

I think heiphens are represented by underscores, so foo-bar becomes foo_bar, however that goes against the standard C# naming convention.

I wouldn't recommend binding query parameters as handler parameters anyway. The cleanest solution is to define a property on your PageModel like so:

// from the Microsoft.AspNetCore.Mvc namespace
[FromQuery(Name = "foo-bar")]
public string FooBar { get; set; }

This way, any time a query parameter matching that name is provided, it will always be bound. Regardless of whether or not the specific handler requested it. Then you can just access the property on your PageModel whenever you need it. So you example method becomes:

public void OnGet()
{
    System.Console.WriteLine($"bar is {FooBar}");
}
like image 162
thomasrea0113 Avatar answered Dec 28 '22 09:12

thomasrea0113


The simplest solution in Razor Pages is to use Request.Query:

public void OnGet()
{
    var data = Request.Query["foo-bar"];
}
like image 30
Mike Brind Avatar answered Dec 28 '22 09:12

Mike Brind