G G*_* Gr 3 c# sql linq asp.net-mvc entity-framework
我有一个博客应用程序,用户可以创建帖子,我使用实体框架从数据库创建模型。在帖子中我有一个条目UrlSlug。
但是,当我检查帖子的详细信息时:
控制器:
public ActionResult Details(int id = 0)
{
Post post = db.Posts.Find(id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
Run Code Online (Sandbox Code Playgroud)
id它返回一个末尾带有以下内容的 url :http://localhost:52202/Post/Details/1
我尝试返回 post.UrlSlug (引发错误)以及更改我的 RouteConfig.cs 文件来使用urlslug(id它确实显示 urlslug,但由于控制器而无法找到页面)。如何更改此设置以便显示 urlslug 而不是 Post Table Id?
路由配置.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
看法:
@for (int i = 0; i < Model.Count(); i += 3)
{
<div class="row">
@foreach (var item in Model.Skip(i).Take(3))
{
<div class="col-md-4 portfolio-item">
<a href="@Url.Action("Details", "Post", new { id = item.Id })">
<img class="img-responsive" src="http://placehold.it/700x400" alt="">
</a>
<h3>
<a href="@Url.Action("Details", "Post", new { id = item.Id })">@Html.DisplayFor(modelItem => item.Title)</a>
</h3>
<p>@Html.DisplayFor(modelItem => item.ShortDescription)</p>
</div>
}
</div>
}
@Html.PagedListPager(Model, page => Url.Action("Index", new { page, pageSize = Model.PageSize }))
Run Code Online (Sandbox Code Playgroud)
编辑
我注意到的一个问题是在这一行:
public ActionResult Details(string urlslug)
{
Post post = db.Posts.Find(urlslug); //find only finds an eitity with a given primary key, how can I change this to find the string urlslug
Run Code Online (Sandbox Code Playgroud)
操作方法不指定 URL,它仅匹配请求。您需要打印 slug:
@Url.Action("Details", "Post", new { slug = item.Slug })
Run Code Online (Sandbox Code Playgroud)
然后添加到路由中以支持你想要的URL结构:
routes.MapRoute(
name: "PostWithSlug",
url: "Post/Details/{slug}",
defaults: new { }
Run Code Online (Sandbox Code Playgroud)
并改变动作方法:
public ActionResult Details(string slug)
{
}
Run Code Online (Sandbox Code Playgroud)
但除此之外,您还需要 URL 中包含 ID。否则,您不能两次使用相同的帖子标题。
| 归档时间: |
|
| 查看次数: |
3659 次 |
| 最近记录: |