如何在asp.net mvc中的url中添加页面标题?
这是控制器:如何在asp.net mvc中的url中添加页面标题?,asp.net,asp.net-mvc,asp.net-core,asp.net-mvc-4,routes,Asp.net,Asp.net Mvc,Asp.net Core,Asp.net Mvc 4,Routes,这是控制器: private MyCmsContext db; public PageRepository(MyCmsContext context) { this.db = context; } public IEnumerable<Page> GetAllPage() { return db.Pages; } public Page GetPageById(int pageId)
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();
这是我的路线,我想在id之后添加新闻标题
例如:新闻
[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();
私有MyCmsContext数据库;
公共页面存储库(MyCmsContext上下文)
{
this.db=上下文;
}
公共IEnumerable GetAllPage()
{
返回db.Pages;
}
公共页GetPageById(int-pageId)
{
返回db.Pages.Find(pageId);
}
这是界面页面存储库:
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();
IEnumerable GetAllPage();
页面GetPageById(int-pageId);
bool插入页(第页);
bool更新页面(第页);
bool DeletePage(第页);
bool DeletePage(intpageid);
作废保存();
这是在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>
如果您想从url中省略“点”和您所想的任何内容,只需在扩展方法中替换您最喜欢的正则表达式代码。请帮助我,这个问题将非常有用