@strin" /> @strin" /> @strin"/>

How to use one index.cshtml for two different methods?

36 Views Asked by At

I am working on a simple website and I have a very simple index page:

@page
@model MyProject.Pages.IndexModel
@{
    ViewBag.Title = "index";
}
<h2>@string.IsNullOrWhiteSpace(Model.FullName)??"Hi":$"Hi, {Model.FullName}"</h2>

Well, there's more but this is the only part that matters.
Now, this also means I have two routes: one to the normal OnGet() for the / route and I need a second one for the "Hello/{fullname}" route. And yes, that "Hello" part is a requirement as there's also some Web API functionality inside this project.
The code-behind is also easy:

public class IndexModel() : PageModel
{
    public string? FullName { get; set; }

    public void OnGet()
    {
    }
}

This isn't too complex and provides the / route. But how do I handle the "Hello/{fullname} route?
Keep in mind that this is a simplified version of this page. It has a lot more code inside that deals with various menus and calling several of the API functions and more.
My problem is also that this layout has been dictated by my management so it might be bad, but I can't do much about that.


The logic behind this is that the page allows the user to log in, which happens through the API calls. So, no page refresh. When the user logs in, the JavaScript will modify the URL from "http://localhost/" to "http://localhost/Hello/SomeName". So, if the user refreshes, that name is still visible and the index page will show the user name and check if the login token is still valid. If not, the login pop up again.

1

There are 1 best solutions below

0
Mike Brind On BEST ANSWER

You can pass the FullName value as a nullable parameter and bind it to the FullName property. The changes you need to make are:

  1. Register an additional route template for the Index page in Program.cs

    builder.Services.AddRazorPages()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Index", "Hello/{fullname?}");
        });
    
  2. Add a BindProperty attribute to the FullName property in the IndexModel class, ensuring that it is a binding target in GET requests:

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

More Information