Search code examples
asp.net-core-mvc

ASP.NET Core: getting url params not firing constructor


In one of my pages I am creating the link to the next page like this:

 <div class="joboffer" onclick="location.href='/Jobs/JobOverview?id=@elem.Id';" style="cursor: pointer;">
     <p>@elem.Title</p>
 </div>

This opens the correct page.

This page has a constructor which looks like this:

public async Task<IActionResult> OnGetid(string id)
{
    if (!_2_LogIn.IsLoggedIn)
    {
        await Response.WriteAsync("<script>alert('Nicht so schnell!!!')</script>");
        return BadRequest();
    }
    else
    {
        // gets the url params 
        return Page();
    }
}

Unfortunately, even though the page is opened with the url "?id=xxxxx", the constructor that is supposed to catch the params is never called.

Why is that?

Best,

J


Solution

  • From your code, OnGetId method is not a constructor, it seems like a OnGet method in razor page.

    For example, I have this method in my Privacy page:

    public async Task<IActionResult> OnGetId(string id)
    {
        if (!_2_LogIn.IsLoggedIn)
        {
            await Response.WriteAsync("<script>alert('Nicht so schnell!!!')</script>");
            return BadRequest();
        }
        else
        {
            // gets the url params 
            return Page();
        }
    }
    

    If I want to pass value to this method via route, I can use:

    <a class="nav-link text-dark" asp-page="/Privacy" asp-page-handler="Id" asp-route-id="xxx">Privacy</a>
    

    Or

    <div class="joboffer" onclick="location.href='/Privacy?id=xxx&handler=Id';" style="cursor: pointer;">
        Privacy
    </div>
    

    to pass value.