【问题标题】:How to generate URL using Html.ActionLink with Forward Slashes instead of QuestionMark如何使用带有正斜杠而不是 QuestionMark 的 Html.ActionLink 生成 URL
【发布时间】:2017-09-09 08:38:39
【问题描述】:

我正在尝试生成带有正斜杠的 URL,如下所示

@Html.ActionLink("Details", "Details", new { id = item.StudentID, name = item.FirstName }) 

期望的结果:

http://www.example.com/Students/Details/3/ttcg
http://www.example.com/Students/Details/4/john
http://www.example.com/Students/Details/5/ronaldo

当前结果:

http://www.example.com/Students/Details/3?name=ttcg

使用 RouteAttribute 的控制器动作

[Route("Students/Details/{id}/{name?}")]
    public ActionResult Details(int? id, string name)
    {
        if (id.HasValue == false)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Student student = _studentService.GetDetail(id.Value);
        if (student == null)
        {
            return HttpNotFound();
        }
        student.FirstName += name;
        return View(student);
    }

目前,我通过使用此代码作弊以获得所需的结果。

<a href="Students/Details/@item.StudentID/@item.FirstName" >Details</a>

有没有更好的方法来生成我想要的所需网址?

根据这篇帖子URL With RouteConfig.cs,我是否必须在 RouteConfig 文件中添加新路由?是不是说RouteAttribute不支持这种URL生成方式?

【问题讨论】:

  • 更改 RouteConfig.cs 后不工作?
  • 我还没有更改 RouteConfig.cs。但我想在做之前先确认一下。由于我已经在使用 RouteAttribute,我不想在 RouteConfig.cs 中再次声明它
  • 您可以更改 routes.MapRoute 并尝试,无论它是否有效。

标签: c# razor routing asp.net-mvc-5


【解决方案1】:

在 RouteConfig.cs 中启用属性路由

routes.MapMvcAttributeRoutes();

添加后你会得到想要的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多