routesrazormodelrazor-pages

How I can pass just an integer to my razor view without creating a model in razorpage


I have a Razor view (without backend .cs file) that has a model of type Int32. It's name is Index in folder Types:

@page
@model Int32

I want to pass an integer to above page by a link like:

<a  asp-page="types/index" asp-route-id="0" class="btn-warning btn">GoPage</a>

This code returns an error:

A suitable constructor for type 'System.Int32' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided


Solution

  • Models don’t work like that. A HTML hyperlink can’t just “pass” an integer or any other data to the server. The int can only be encoded within the link itself, either in the query string (?id=69) or as a route parameter. Your syntax in the tag helper does exactly that.

    In your view you can then access the value from the named route parameter, which is nice because you can enforce it to be a valid integer:

    @page "{id:int}"
    
    <h1>You're looking at ID @Request.RouteValues["id"].</h1>
    

    Your url will also look nicer this way. Note that the value itself will still be a String.

    Or you can go the query string way, which will allow anything, including nothing at all:

    @page @* this is necessary. without it you don’t get the Request property. *@
    
    <h1>You're looking at ID @Request.RouteValues["id"].</h1>
    

    Since you’re using the page directive, there will be a page model. You just don’t see it in your code.

    Depending on the page directive, the <a> TagHelper will generate the url accordingly. If the targetted Page doesn’t have route parameters, you’ll get the query string.