I'm using asp-route-id to pass the id value to the controller which will return me a view with information about "blog" with same id.
Everything works but i don't like how "Url" looks!
How can I change "Url" like this https://localhost:5001/Blog/Blog/8 to this https://localhost:5001/Blog/Blog/title_of_blog ?
Details:
there is a list of blogs blog/list
html code for each of them:
@model Blog <div class="col-12 col-md-6 col-lg-6" style="padding-top: 30px"> <div class="card card-shadow my-4 card_blog"> <img src="~/img/originals/img-09.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">@Model.Title</h5> <p class="card-subtitle">@Model.Date.ToString("dd-MM-yyyy")</p> <p class="card-text">@Model.Description</p> <a asp-route-id="@Model.BlogID" asp-controller="Blog" asp-action="Blog" class="a_s_btn myBTN">Read More</a> </div> </div> </div>I'm clicking on tag
<a asp-route-id="@Model.BlogID" asp-controller="Blog" asp-action="Blog" class="a_s_btn myBTN">Read More</a>here is the "Blog" action in the "Blog" cotroller
public IActionResult Blog(int id) { var blogModel = new BlogsListViewModel(); blogModel.Blogs = repository.Blogs.OrderBy(p => p.BlogID).Where(p => p.BlogID == id); return View(blogModel); }The "Blog" action return to me a page with information about blog with "BlogID" = 8 blog page with own information
You can think of this problem in three parts:
1. Configure your website to handle new routing
In startup.cs you will find a section of the
Configuremethod that is similar to:Add a new route type to that ( but keep the existing route if you still want to use that for other places of the site.):
2. Generate the URL
When putting the link into a page use markup like:
3. Make sure the controller will receive and handle the new route
Instead of your current controller method that expects an id parameter, you need to take a blogTitle string:
Of course, the details of how you retrieve by title may change, depending on your variable. The important bit here is that the parameter name matches the new portion of the route provided in step 1.
Don't forget
Keep in mind that you will now need to handle special characters in your url. Urls can't contain some characters that your users could add to their blog title, such as ampersands or non-ascii characters. ( Characters allowed in a URL )