asp.net - 如何在 asp.net mvc 中的 url 中添加页面标题?

标签 asp.net asp.net-mvc asp.net-core asp.net-mvc-4 routes

这是 Controller :

这是我的路线,我想在 id 之后添加新闻标题

例如:news/55/مایکروساوت،سرویس دو

  [Route("News/{id}")]
        public ActionResult ShowNews(int id)
        {

            var news = pageRepository.GetPageById(id);
            if (news == null)
            {
                return HttpNotFound();
            }

            news.Visit += 1;
            pageRepository.UpdatePage(news);
            pageRepository.Save();

            return View(news);
        }

这是存储库页面:

   private MyCmsContext db;

    public PageRepository(MyCmsContext context)
    {
        this.db = context;
    }
    public IEnumerable<Page> GetAllPage()
    {
        return db.Pages;
    }

    public Page GetPageById(int pageId)
    {
        return db.Pages.Find(pageId);
    }

这是接口(interface)页面存储库:

 IEnumerable<Page> GetAllPage();
    Page GetPageById(int pageId);

    bool InsertPage(Page page);
    bool UpdatePage(Page page);
    bool DeletePage(Page page);
    bool DeletePage(int pageId);
    void Save();

最佳答案

这是在 ASP.Net Core 3.1 上测试的: 如果你想有一个漂亮的标题(例如空格被破折号代替),首先创建一个这样的扩展方法:

 namespace BulkyBook.Utility
{
   public static class CleanURLMaker
    {
        public static string CleanURL(this string url)
        {
            // ToLower() on the string thenreplaces spaces with hyphens
            string cleanURL = url.ToLower().Replace(" ", "-");

            // cleanURL = System.Text.RegularExpressions.Regex.Replace(cleanURL , @"\s", "-");
            cleanURL = cleanURL.Replace(" ", "-");
            return cleanURL;
        }
    }
}

然后在您的 view.cshtml 中,在您引用/调用目标的同一位置,您必须传递您的标题,类似这样,但在发送标题之前,通过您在上面创建的扩展方法使其干净漂亮:

@using BulkyBook.Utility
 <a asp-area="Customer"  asp-controller="Home" asp-action="Details" asp-route-id="@item.ID" asp-route-Title="@item.Title.CleanURL()"> Details</a>

上面的代码等同于下面的代码:

<a  href="/HelloWorld/65/this-is-my.first-title"> Details</a>

最后你的 action 方法将是这样的:(注意,如果你只想要一个干净的 URL,则不需要将 Title 作为参数传递给你的 action 方法):

 [Route("HelloWorld/{id}/{Title}")]
    public async Task<IActionResult> Details(int id)
    {
       Product product =await _unitOfWork.productRepository.GetByID(id);
       return View(product);
    }

最后您的链接将是这样的:没有人看到您的区域、 Controller 和操作方法名称

~/HelloWorld/23/this-is-my.first-title

如果您想从 url 中省略“点”和您的想法,只需在扩展方法中替换您最喜欢的正则表达式代码即可。

关于asp.net - 如何在 asp.net mvc 中的 url 中添加页面标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62227312/

相关文章:

c# - Visual Studio 多项目解决方案问题

c# - CS0103 : The name 'CType' does not exist in the current context

asp.net-mvc - Mvc Mini Profiler 对带有和不带有 RouteBasePath 的文件的请求

c# - .Net Core 覆盖通用 Controller 的 Controller 路由

Asp.Net MVC3 - FormsAuthentication,如何在浏览器关闭时使 cookie 过期?

asp.net - 将 JSON 发布到 Controller

asp.net-mvc - 共享主机上的 ASP.NET MVC 无扩展 URL? (GoDaddy 等)

c# - 我使用的是什么架构模式/设计?

asp.net-core - 如何在启动时将数据放入 MemoryCache?

azure - VSTS 将 docker-compose 推送到 Azure 容器注册表和 WebApp