ActionLink表现不一致

时间:2015-10-15 09:18:43

标签: asp.net-mvc razor asp.net-mvc-5.2

我有两个控制器,每个控制器都有一个使用route属性的动作。在我看来,我使用@ Html.ActionLink助手来呈现每个动作的链接。但是,其中一个操作无法呈现正确的URL。

这是我到目前为止所做的:

查看

<div class="actionRow row">
    <div class="col-lg-12">
        @Html.ActionLink("Edit", "EditRequest", "Modelling", new { @requestId = Model.RequestId }, new { @class = "btn btn-danger" })
        @Html.ActionLink("Cancel", "Details", "Business", new { @pRef = Model.PRef }, new { @class = "btn btn-info" })
    </div>
</div>

建模控制器

public class ModellingController : Controller
{
    [HttpGet]
    [Route("modelling/{requestId}")]
    public ActionResult EditRequest(int requestId)
    {
    }
}

业务控制器

public class BusinessController : Controller
{
    [HttpGet]
    [Route("business/details-card/{pRef}")]
    public ActionResult Details(string pRef)
    {
    }
}

结果

以这种方式,我在页面上生成以下网址: http://localhost:8061/modelling/3211 http://localhost:8061/business/details?pRef=bds1234

第一个链接是正确的,但我希望第二个链接看起来像 http://localhost:8061/business/details-card/bds1234

更多详情

如果我改变视图以获得以下标记,那么我实际上会生成正确的链接,但是它没有样式 - 原因显而易见。但是,如果我然后尝试添加类详细信息,则会将它们作为查询字符串参数附加到链接。

更改视图

<div class="actionRow row">
    <div class="col-lg-12">
        @Html.ActionLink("Edit", "EditRequest", "Modelling", new { @requestId = Model.RequestId }, new { @class = "btn btn-danger" })
        @Html.ActionLink("Cancel", "Details", "Business", new { }, new { @pRef = Model.PRef })
    </div>
</div>

产生http://localhost:8061/business/details-card/bds1324

进一步改变视图

<div class="actionRow row">
    <div class="col-lg-12">
        @Html.ActionLink("Edit", "EditRequest", "Modelling", new { @requestId = Model.RequestId }, new { @class = "btn btn-danger" })
        @Html.ActionLink("Cancel", "Details", "Business", new { @class = "btn btn-info" } new { @pRef = Model.PRef })
    </div>
</div>

产生http://localhost:8061/business/details-card/bds1234?class=btn btn-info

更多信息

控制器中没有其他控制器,也没有其他操作,我在route.config中正确启用了map属性路由

1 个答案:

答案 0 :(得分:1)

在你的情况下,它有助于添加:

routes.MapMvcAttributeRoutes();

在RouteConfig中:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

在视图中:

@Html.ActionLink("Edit", "EditRequest", "Modelling", new { @requestId = 1 }, new { @class = "btn btn-danger" })
@Html.ActionLink("Cancel", "Details", "Business", new { @pRef = "123" }, new {@class = ""})