如何使用带有正斜杠而不是QuestionMark的Html.ActionLink生成URL

时间:2017-04-13 09:34:08

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

我正在尝试使用正斜杠生成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生成?

1 个答案:

答案 0 :(得分:0)

在RouteConfig.cs中启用属性路由

routes.MapMvcAttributeRoutes();

添加后,您将获得所需的结果。