问题
在我的项目中,我决定使用 db 存储实体“Section”来实现自定义菜单提供程序。因此该部分映射到以下模型:
public class TopMenuItemModel : BaseTrivitalModel
{
public TopMenuItemModel()
{
ChildItems = new List<TopMenuItemModel>();
}
public int ItemId { get; set; }
public string RouteUrl { get; set; }
public string Title { get; set; }
public string SeName { get; set; }
public IList<TopMenuItemModel> ChildItems { get; set; }
}
以及模型的视图:
@model TopMenuModel
<nav id="main-nav">
<a href="@Url.RouteUrl("HomePage")">@T("HomePage")</a>
@foreach (var parentItem in Model.MenuItems)
{
<a href="@Url.RouteUrl("Section", new { seName = parentItem.SeName, sectionId = parentItem.ItemId })">@parentItem.Title</a>
}
</nav>
我的默认路线是:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Trivital.Web.Controllers" }
);
菜单控制器:
public class CommonController : BaseTrivitalController
{
...
public ActionResult TopMenu()
{
var sections = _sectionService.GetCollectionByParentId(0, true);
var model = new TopMenuModel();
model.MenuItems = sections.Select(x =>
{
var item = new TopMenuItemModel()
{
ItemId = x.Id,
Title = x.GetLocalized(s => s.Title, _workContext.WorkingLanguage.Id, true, true),
SeName = x.GetSeName(),
RouteUrl = "",
};
return item;
})
.ToList();
return PartialView(model);
}
}
}
现在我有一个 SectionController ,其中有一个 ActionResult 方法:
//section main page
public ActionResult Section(string seName)
{
var section = _sectionService.Get(1);
if (section == null || section.Deleted || !section.Published)
return RedirectToAction("Index", "Home");
//prepare the model
var model = PrepareSectionPageModel(section);
return View(model);
}
我当前的部分路线(给我主机/sectionSeName-id):
routes.MapLocalizedRoute(
"section", // Route name
"{SeName}"+ "-" + "{sectionId}", // URL with parameters
new { controller = "Sections", action = "Section" },
new { sectionId = @"\d+" }
);
现在我需要让我的 Url 看起来像这样(没有 id,只有部分名称):
主机/部分SeName
无论如何要在 url 中隐藏 ID 以使 url 看起来对 SEO 友好,但可用于控制器?