【发布时间】:2015-02-27 17:41:45
【问题描述】:
我遇到了路由问题。我有新闻控制器,我可以从 url http://localhost/News/Details/1/news-title(slug) 阅读新闻的详细信息。这里暂时没有问题。但我创建了一个名为 Services 和 Index 操作的控制器。路线配置:
routes.MapRoute(
"Services",
"Services/{id}",
new { controller = "Services", action = "Index" }
);
当我的索引操作是
public ActionResult Index(string title)
{
return View(title);
}
我在浏览器中手写localhost:5454/Services/sometext,它可以工作。
但是当我将索引操作更改为
public ActionResult Index(string title)
{
Service service = _myService.Find(title);
ServiceViewModel = Mapper.Map<Service , ServiceViewModel >(service );
if (service == null)
{
return HttpNotFound();
}
return View(serviceViewModel);
}
我收到 URL localhost/Services/ITServices 的 Http 错误 404。
我可以从管理页面添加此服务及其标题(例如 ITServices)。 然后我在我的主页中为服务链接做 foreach
@foreach (var service Model.Services)
{
<div class="btn btn-success btn-sm btn-block">
@Html.ActionLink(service.Title, "Index", new { controller = "Services", id = service.Title })
</div>
}
但我无法在localhost/Services/ITServices 中显示页面。
当我点击链接时,我想转到页面 localhost/Services/ITServices,它必须像新闻一样显示内容(可以从管理页面添加)。但我不想像新闻中那样将它与动作名称和 ID 一起使用。我怎样才能做到这一点?
编辑
好的。我在存储库中添加FindByTitle(string title)。我在 RouteConfig 和主页视图的链接中将 id 更改为 title。然后在我的域模型中删除 Id 并将 Title 更新为 [Key]。现在它起作用了。从管理页面添加新标题时,只需通过远程验证检查可能的标题重复项。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-routing action