2

I'm trying have multiple menu links hit the same razor page, but send different parameters to return different results from the database.

Normally I would just append the value to a querystring and retrieve it when the new page link is clicked, but I don't know how razor pages do this. For example, I want to go to my razor page called, CourseList.cshtml, and pass, Accounting, as the value so I can only pull back accounting courses.

asp-page="/CourseList?ccat=accounting"

I know I could make separate CourseList pages for each course category, but that sounds dirty and will have higher maintenance as new categories are added.

<ul class="navbar-nav flex-grow-1">
                        <li class="nav-item dropdown">
                        <a class="nav-link text-dark dropdown-toggle" 
href="#" id="navbaddrop" data-toggle="dropdown">
                                Courses
                            </a>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" asp-page="/CourseList?ccat=accounting">Accounting</a>
                                <a class="dropdown-item" asp-page="/CourseList?ccat=general">General</a>
                            <a class="dropdown-item" asp-page="/CourseList?ccat=it">IT</a>
                            <a class="dropdown-item" asp-page="/CourseList?ccat=manufacturing">Manufacturing</a>
                        </div>
                    </li>
</ul>

1 Answer 1

1

If you want the value to appear in a query string, pass it to the asp-route-* parameter of the anchor tag helper:

<a class="dropdown-item" asp-page="/CourseList" asp-route-ccat="accounting">Accounting</a>

The * is replaced with the name of the parameter.

Alternatively, you can pass it as a route parameter (a segment in the URL) by specifying a route data parameter in the Razor page as part of the @page directive:

@page "{ccat}"

Then the generated links will look like this:

CourseList/accounting
CourseList/general

In the page itself, you add a property representing the parameter with the BindProperty attribute applied to it:

public class CourseListModel : PageModel
{
    [BindProperty(SupportsGet=true)]
    public string Ccat { get; set; }

    ...

Model binding will automatically assign the query string value to the public property. More information:

Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I needed! Thank you so much. I've been doing classic asp and asp.net for so long that I'm struggling to bend my brain around this new stuff. This was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.