Search code examples
asp.net-corerouteshrefrazor-pages

Show title of news in destination page url in ASP.NET Core Razor page


i use this code to make a href link for show my news site

<a asp-page="ShowNews" asp-route-Id="@item.NewsID">

and finally in my adress bar get this adress:

https://localhost:44390/ShowNews?Id=33

but i want get values in address bar like this:

https://localhost:44390/ShowNews/myTitleNews

or

https://localhost:44390/myTitleNews


Solution

  • You can change the route parameter from Id to the Title.

    <a asp-page="ShowNews" asp-route-title="@item. Title">
    

    Then in the ShowNews page's OnGet method, according to the title to find the News. The could as below:

        public async Task<IActionResult> OnGetAsync(string? title)
        {
            if (title == null || _context.NewsModel == null)
            {
                return NotFound();
            }
    
            var newsmodel = await _context.NewsModel.FirstOrDefaultAsync(m => m.Title== title);
            if (newsmodel == null)
            {
                return NotFound();
            }
            else
            {
                NewsModel = newsmodel;
            }
            return Page();
        }
    

    And in the ShowNews.chstml page, set the @page directive like this:

    @page "/news/ShowNews/{title}"
    

    The output as below:

    enter image description here