Search code examples
asp.net-mvcasp.net-coreasp.net-identity

ASP.NET Core MVC pass a url parameter to the POST


I have a Blazor Server app. It uses the ASP.NET Identity Library which is ASP.NET Core MVC. I am trying to pass a parameter to register so a URL like /identity/account/Register?follow=uniqueId gives me the parameter follow=uniqueId.

In Register.cshtml.cs (class RegisterModel) I have:

public async Task OnGetAsync(string returnUrl = null, string following = null)
{
    ReturnUrl = returnUrl;
    Following = following;
    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null, string following = null)
{
    // ...
}

The value from the url is passed in to OnGetAsync() fine. But when OnPostAsync() is called, it passes in a null for following and the object property Following is also null.

How do I get that parameter in OnPostAsync()?


Solution

  • According to your description, the reason why the following is always null is you don't set the [FromQuery] attribute and not use the right query string.

    Inside the url your querystring is follow not following which will not bind well.

    I suggest you could modify the method like below:

    public async Task<IActionResult> OnPostAsync(string returnUrl = null, [FromQuery]string following = null)
    {
        // ...
    }
    

    enter image description here


    Update: As you said, POST requests do not automatically include URL parameters unless you set it inside the from action attribute.

    Since you don't share how you post the request, I provide two way which could make this post work well.

    More details, you could refer to below example:

    1.You set the follow query string inside the form tag action like below:

    <form action="/register?follow=uniqueId" method="post">
    
        <input type="submit" value="Submut"/>
        
    
    </form>
    

    2.If you are using the razor page and still want to use it, you could refer to below :

    <form asp-route-returnUrl="@Model.ReturnUrl" method="post" asp-route-follow="@Model.Follow">
    

    3.If you are using the razor page and post it inside the razor page not blazor, you could use hidden field and use the bind parameter like below:

    <form method="post">
    
        <input type="hidden" asp-for="Following"  value="test"/>
        <input type="submit" value="Submut" />
    
    
    </form>
    

    Inside the razor page.cs add below codes:

        [BindProperty]
        public string Following { get; set; }