Search code examples
c#html.netrazorvisual-studio-2022

Blazor .NET C# can't get input from html <form>


When I try to get input from the user using the html <form> thing, I get the error:

CS0103 Der Name "Request" ist im aktuellen Kontext nicht vorhanden.

This translates to

CS0103 The name "Request" does not exist in the current context

This is my C# code:

@{
    double distance = 0;

    if (Request.Query.ContainsKey("distance"))
    {
        double.TryParse(Request.Query["distance"], out distance);
    }

My HTML markup:

<p>Enter distance:</p>
<form method="get">
    <input type="text" name="distance" />
    <button type="submit">Calculate</button>
</form>

Normally this should get the user input, but it doesn't


Solution

  • The error means compiler cannot find the class Request

    To get text input :

        @inject NavigationManager NavigationManager
    
    @{
        double distance = 0;
    
        var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
    
        if (query.ContainsKey("distance"))
        {
            double.TryParse(query["distance"], out distance);
            Console.WriteLine(distance.ToString());
        }
    }
    
    <p>Enter distance:</p>
    <form method="get">
        <input type="text" name="distance" />
        <button type="submit">Calculate</button>
    </form>