【问题标题】:Url.Action(action,controller,routeValues) doubling up ID in URLUrl.Action(action,controller,routeValues) 在 URL 中加倍 ID
【发布时间】:2011-04-20 18:06:43
【问题描述】:

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

/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

【问题讨论】:

  • routeValues 中填充了什么?
  • 对不起,只是一个像这样的匿名类型:New With { .id = "tabled" }
  • 您应该向我们展示您的路线规则。
  • 我敢打赌这是问题的根源,请参阅上面我编辑的帖子。
  • 会不会是当前页面的.statusTabled?我的意思是当前的网址是/Proposals/List/Tabled

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


【解决方案1】:

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

因此,当当前状态为 Tabled 并且您没有在您传递的新 routeValues 中重置它时,它仍然会使用它..

但是由于您也传递了一个 id,它也会添加它..

你需要通过New With {.id = Model.StatusFilter, .status = nothing}

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

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

【讨论】:

  • 实际上,我认为我真正需要做的是回顾我的方法并简化这里的事情。我是 MVC 的新手,对我想要完成的事情有点太复杂了。
猜你喜欢
  • 2016-12-22
  • 1970-01-01
  • 2011-05-30
  • 2014-08-03
  • 2018-06-04
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多