Try to access URL parameter inside razor page

Viewed 429

I send an URL through an email to access a form with the parameter name "email". I try to access the email parameter inside the razor page.

This is what I pass as URL:

https://localhost:44339/Home/LecturerRegister?email=pasindu@gmail.com'

Then I access the email parameter by using ViewContext.RouteData.Values["email"]

<input type="email" required class="form-control" name="Email" value="@(ViewContext.RouteData.Values["email"])">

But I can't access the parameter value by this method. It's return nothing.

2 Answers

The recommended way to work with data passed in URLs is to use Model Binding. In this example, you should add a public property to your PageModel class representing the email and mark it with the BindProperty attribute, opting in to binding in GET requests:

[BindProperty(SupportsGet=true)]
public string Email { get; set; }

Then use an input tag helper to generate your input, assigning the public the asp-for attribute:

<input asp-for="Email" class="form-control" />

the tar will take case of generating the correct name and attributes and will assign the value from the bound property.

More about model binding in Razor Pages: https://www.learnrazorpages.com/razor-pages/model-binding More about input tag helpers: https://www.learnrazorpages.com/razor-pages/tag-helpers/input-tag-helper

Note: you could also use Request.Query["email"], but model binding is the correct way to do this.

Can you try this code:

value="@ViewContext.RouteData.Values["email"].ToString()"
Related