【问题标题】:How to pass in ID with Html.BeginForm()?如何使用 Html.BeginForm() 传入 ID?
【发布时间】:2009-05-18 15:33:19
【问题描述】:

ASP.NET MVC 我正在使用 HTML 助手

Html.BeginForm("ActionName", "Controller", FormMethod.Post);

但我需要发布到:/controller/action/23434

如何传递 ID?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    马特应该可以正常工作。但是,如果您仍然传入FormMethod.Post,则需要这样做:

    Html.BeginForm("action","controller", new { Id = 12345 }, FormMethod.Post);
    

    颠倒第三个和第四个参数将导致Id 被视为属性而不是路由值。

    【讨论】:

    • 我在使用这种方法时丢失了现有的路由值。假设我的网址是/controller/action?type=golden,表单目标(使用你的方式)现在变成/controller/action/12345,而我希望它是/controller/action/12345?type=golden。你知道有什么方法可以保留现有的路由值并附加我自己的吗?
    • @Aki 尝试将type 添加为表单中的隐藏字段,它应该会一起发送。
    • 我可以,但你知道那不是我的问题。我的查询字符串中没有必要只有 type,我可以有 N 个参数,在不同的操作中可能会有所不同。进入所有这些操作并将查询参数添加为隐藏字段将是一个真正的痛苦。
    【解决方案2】:

    Html.BeginForm("action", "controller", new {Id = 12345})

    【讨论】:

    • 检查参数名称 routeValues - 确保您使用的不是 htmlAttributes。
    【解决方案3】:
    Html.BeginForm("action", "controller", new { id = ViewBag.FileID },
    FormMethod.Post, new { id = "feedbackform" })
    

    至于查询字符串?type=golden,我不知道该怎么做。当然,查询是一种获取,它破坏了FormMethod.Post 的全部目的。我的意思是,如果你想要查询字符串数据,你可以使用FormMethod.Get,这可能就是你要找的。

    此外,您可以避免html.beginform 并使用表单标签手动执行查询字符串、get + post。

    第三,如果你使用表单,你可以做一个隐藏字段:

    [input type=hidden name="type" value="golden"]
    

    然后,当按下提交按钮时,该值作为表单变量正确传递。

    【讨论】:

      【解决方案4】:
      <!-- ACTION: Category/Update/Id | Method:Post-->
      @using (Html.BeginForm("Update", "Category",new {Id = @Model.Id },FormMethod.Post)){}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-27
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 2017-05-06
        • 2017-08-24
        • 2011-04-10
        相关资源
        最近更新 更多