asp.net - 如何在asp.net mvc的url中添加页面标题?
问题描述
这是控制器:
这是我的路线,我想在 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);
}
这是接口页面存储库:
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>
最后您的操作方法将是这样的:(注意,如果您只想要一个干净的 URL,则无需将 Title 作为参数传递给您的操作方法):
[Route("HelloWorld/{id}/{Title}")]
public async Task<IActionResult> Details(int id)
{
Product product =await _unitOfWork.productRepository.GetByID(id);
return View(product);
}
最后,您的链接将是这样的:没有人看到您的区域、控制器和操作方法名称
~/HelloWorld/23/this-is-my.first-title
如果您想从 url 中省略“点”以及您的想法,只需在扩展方法中替换您最喜欢的正则表达式代码。
推荐阅读
- java - android中的ecdh密钥生成
- python - 使用 For 循环调用带有一系列参数的函数
- ionic4 - 如何在 ionic 4 中实现 seekto 功能?
- html - 如何使用 encoding/xml 在 Go 中忽略 html 属性?
- kotlin - 检查空值后显示空值安全错误
- oracle - 如何从有吸引力的报告中显示下载的 pdf 中的页眉值
- c# - 仅带数字的制表符的文档签名
- python - apriori算法中确定频繁项集生成的最小支持阈值
- c# - 在 C# 中向操作系统语言添加自定义键盘布局
- javascript - lodash orderBy 尝试使其不区分大小写时出现问题