Url.Action(action,controller,routeValues)将URL中的ID加倍

时间:2011-04-20 18:06:43

标签: asp.net-mvc asp.net-mvc-3 razor html-helper

我在HTML扩展帮助程序中使用以下代码(取自Stackoverflow帖子:Action Image MVC3 Razor)来构建操作链接。我的Url.Action()方法返回一个url,它在路由中都有routeValues,并且附加到url上,如下所示:

/Proposals/List/Tabled?id=Tabled

当我想要的只是

/Proposals/List?id=Tabled

有关为什么要这样做的任何建议?

更新

来自Global.asax文件的路由规则。这一定是它为什么这样做的原因,但为什么它变得双倍对我来说仍然是一个谜。

routes.MapRoute( _
    "ProposalsList", _
    "Proposals/List/{status}", _
    New With {.controller = "Proposals", .action = "List", .status = "Pending"} _
    )

更新

这是我对方法的调用,我将方法定义添加到下面的代码中。

@Html.ActionImage("Proposals", "List", New With {.id = Model.StatusFilter}, "~/images/" + Model.ImageFile, "Count", 32, 32, Model.ProposalsCount.ToString + " " + Model.StatusFilter + " Proposal(s)")

这是我的代码:

    <Extension()> _
    Public Function ActionImage(ByVal html As HtmlHelper, ByVal controller As String, ByVal action As String, ByVal routeValues As Object, ByVal imagePath As String, ByVal alt As String, ByVal width As Integer, ByVal height As Integer, ByVal text As String) As MvcHtmlString                
            Dim url = New UrlHelper(html.ViewContext.RequestContext)
            Dim imgHtml As String
            Dim anchorHtml As String
            Dim imgbuilder = New TagBuilder("img")

            imgbuilder.MergeAttribute("src", url.Content(imagePath))
            imgbuilder.MergeAttribute("alt", alt)
            imgbuilder.MergeAttribute("width", width)
            imgbuilder.MergeAttribute("height", height)
            imgHtml = imgbuilder.ToString(TagRenderMode.SelfClosing)

            Dim anchorBuilder = New TagBuilder("a")
            anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues))
            anchorBuilder.InnerHtml = imgHtml + "<br/>" + text
            anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal)

            Return MvcHtmlString.Create(anchorHtml)
    End Function

1 个答案:

答案 0 :(得分:3)

当您将routeValues传递给url.action方法时,它将使用这些值来覆盖当前定义的值(当前页面的请求上下文中的 )。

因此,当当前状态为Tabled并且您未在您传递的新路由值中重置时,它仍会使用它...

但是既然你传递了一个id,它也会添加它......

您需要传递New With {.id = Model.StatusFilter, .status = nothing}

层次结构是({em> 来自http://forums.asp.net/t/1328683.aspx

  1. Url.Action调用中指定的值,然后是
  2. 在当前页面的请求上下文中指定的值,然后是
  3. 路线的默认值。