英文:
ASP.NET Core: getting url params not firing constructor
问题
在我的一个页面中,我创建下一页的链接如下:
<div class="joboffer" onclick="location.href='/Jobs/JobOverview?id=@elem.Id';" style="cursor: pointer;">
    <p>@elem.Title</p>
</div>
这会打开正确的页面。
这个页面有一个构造函数,看起来像这样:
public async Task<IActionResult> OnGetid(string id)
{
    if (!_2_LogIn.IsLoggedIn)
    {
        await Response.WriteAsync("<script>alert('Nicht so schnell!!!')</script>");
        return BadRequest();
    }
    else
    {
        // 获取URL参数
        return Page();
    }
}
不幸的是,尽管页面是通过URL "?id=xxxxx" 打开的,但应该捕获参数的构造函数从未被调用。
为什么会这样?
最好的,
J
英文:
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
答案1
得分: 0
From your code, OnGetId method is not a constructor, it seems like an OnGet method in a 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 a value to this method via the 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 the value.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论