Home > Enterprise >  Try to access URL parameter inside razor page
Try to access URL parameter inside razor page

Time:04-26

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

This is what I pass as URL 'https://localhost:44339/Home/[email protected]'

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

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

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

CodePudding user response:

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"  />

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.

CodePudding user response:

Can you try this code : value="@ViewContext.RouteData.Values["email"].ToString()"

  • Related