Reputation: 3149
This question has been asked earlier and as I am new to Razor Pages
, unable to figure out how I can make the required (Silly one). So here it's: I've a razor page
where I show a list of data where I've to make the page routing or url as follows:
@foreach (var item in Model.Data)
{
<a href="./search_details/id/@item.Id">@item.Name @item.City @item.State</a>
}
So pretty simple, so in the Startup.cs
, I tried to do the following to make it work. Unfortunately failed:
//This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc();
services.AddEntityFrameworkSqlite().AddDbContext<MyDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMvc().AddRazorPagesOptions(options =>
{
//Here is the configured routing that I tried
options.Conventions.AddPageRoute("/search_details", "/search_details/id");
});
}
I would like to return the url as ./search_details/id/1002 and in the back-end, did this to get the query string value:
string id = this.RouteData.Values["id"].ToString();
This is pretty basic, but as I said failed (Failed means in the back-end, the query string doesn't hit while debugging). I've one more scenario and this thing is bothering me right now the most. My requirement is to hide the page name as well. Something like this:
localhost:8080/search_details/id/1002
To
localhost:8080/1002
Is there appropriate way where I can accomplish that? I understand that's a bad practice for other purposes but for the time being, I would go with it.
N.B: I am not willing to do it in the client-end unless there is no alternate. If possible, better with something server-side using C#
.
Upvotes: 0
Views: 1205
Reputation: 27528
You can use Route Templates in Razor pages :
https://www.learnrazorpages.com/razor-pages/routing
Comment out this line options.Conventions.AddPageRoute
, and in your search_details
page add nullable parameter :
@page "{id?}"
In cs file , you can get route data like :
public void OnGet(string id)
{
}
For the second requirement, you can add template like :
options.Conventions.AddPageRoute("/search_details", "{id}");
So that localhost:8080/1002
will redirect to search_details
page and you will get id
as route data also .
Upvotes: 3