【问题标题】:ASP.NET MVC 4 to Generate URL Formate as Controller/Action/IDASP.NET MVC 4 生成 URL 格式作为控制器/动作/ID
【发布时间】:2014-04-06 04:47:02
【问题描述】:

我将默认路由定义为

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

我想在 html 中生成这样的 url -

<form action="/app/Request/c35d4520-ba0b-452f-837b-a00046f40647 method="post"> 

但如果我像这样编写 Razor 页面 -

@using (Html.BeginForm("Default", "Request", FormMethod.Post, new { id = ViewBag.AppId }))

渲染的html是-

<form action="/app/Request" id="c35d4520-ba0b-452f-837b-a00046f40647" method="post"> 

如何强制剃须刀将 url 生成为控制器/动作/ID 格式?

谢谢

【问题讨论】:

  • @{string a = ViewBag.a;} @using (Html.BeginForm("Default/" + a, "Request", FormMethod.Post, new { })) { } 懒人喜欢我会这样做。但是,如果应用程序的任何地方都需要这样做,您应该编写一个自定义帮助器。
  • BeginForm() 的前 2 个参数是 string actionName and string controllerName,并与 url 中的 {action}{controller} 相关。您的应用程序是否有 appControllerRequest 方法来匹配 /app/Request/?如果是这样,Html.BeginForm("Request", "app", ...).
  • @JonathanLonowski,谢谢。我没有一个带有名为 Request 的方法的 appController 来匹配 /app/Request/。
  • @Lakshay,谢谢。如果我这样做,我会收到一个错误,因为 - 编译器错误消息:CS1973:'System.Web.Mvc.HtmlHelper>' 没有名为 'BeginForm' 但出现的适用方法具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法。我不知道为什么错误提到了 RequestDto 类。我没有在该行中调用类。
  • @Don 我在发表评论之前自己尝试过,它工作正常..抱歉不知道为什么会发生这种情况

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


【解决方案1】:

尝试使用Html.BeginRouteForm

@using (Html.BeginRouteForm("Default", new { controller = "foo", action = "bar" }, FormMethod.Post, new { id="foo", enctype="multipart/form-data", accept_charset="utf-8" }))
{
}

【讨论】:

    【解决方案2】:

    问题在于您在Html.BeginForm 调用中排列参数的方式。根据您输入的参数,您当前正在调用

    Html.BeginForm(actionName, controllerName, formMethod, htmlAttributes)
    

    因此,new { id = ViewBag.AppId } 被视为 htmlAttributes。这就是为什么id 被重新渲染为表单标签中的一个属性。

    相反,您应该如下交换方法和 id 的位置

    Html.BeginForm("Default", "Request", new { id = ViewBag.AppId }, FormMethod.Post))
    

    让我知道它是否适合你:)

    【讨论】:

      【解决方案3】:

      问题已经被一个函数解决了-

      protected ActionResult RedirectToAppAction(string controllerName)
      {
          return this.Redirect(string.Format("/App/{0}/{1}", controllerName, this.Id));
      }
      

      【讨论】:

        猜你喜欢
        • 2013-08-04
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 2010-10-10
        • 1970-01-01
        相关资源
        最近更新 更多