Written by Mark Pringle | Last Updated on Tuesday, December 06, 2022

C# Programming ASP.NET Version: 6.0 Tutorial Articles

When building websites, developers frequently generate URLs from database content. Often, that database content contains a hashtag (#). For instance, this website has a category called “C# Programming.” We generate a rewritten URL using that category field from the database and then use it to query the database. However, we do not want the hashtag to display in the URL because it will casue an error. How does a programmer deal with this problem using ASP.NET MVC and C#?

One solution is to encode and decode the string containing the hashtag. Unfortunately, that is not a pretty or readable solution. A more user-friendly solution is to replace the hashtag at runtime with something more elegant.

Replace the Hashtag in the URL

Replace the hashtag in the string with something more readable or nothing, depending on your needs. In this example, we are replacing "c#" in the link with "csharp." This will cause the URL to read "/category/csharp-programming" instead of "/category/c#-programming," which causes an error in the browser at runtime because of the #. 

@foreach (var item in Model)
        {
            <li class="list-group-item">
                <a href="/category/@item.Category.ToLower().Replace(" ","-").Replace("c#","csharp")">@item.Category</a>
            </li>
        }

Since we are using this category as a query string, we need to put the string back to its original state before querying the database. We will do this in the controller. You can see in the code below that we've replaced "csharp" with "c#" to determine if the category from the database and the query string match. 

        // GET: Search Results by Category
        public async Task<IActionResult> Category(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                //Return the query string id to its original form
                var idCategory = id.Replace("-", " ").Replace("csharp", "c#").ToLower();
                var category = await _context.TableCategories
                .FirstOrDefaultAsync(m => m.Category.ToLower() == idCategory);

                TempData["Category"] = category?.Category;
                TempData["Description"] = category?.Description;

                if (!string.IsNullOrEmpty(id) && category?.Category.ToLower() == idCategory)
                {
                    var results = await _context.ArticleSelect.FromSqlInterpolated($"exec dbo.ArticleSelectCategory @category={idCategory}").ToListAsync();
                    return View(results);
                }
                else
                {
                    return NotFound();
                }
            }
            else
            {
                return View();
            }
        }

That's it. Now, we have created a pretty and user-friendly URL without a hashtag.

Remove Hashtag from a URL