【问题标题】:Html.BeginForm and adding propertiesHtml.BeginForm 和添加属性
【发布时间】:2010-09-18 00:17:48
【问题描述】:

如何将enctype="multipart/form-data" 添加到使用<% Html.BeginForm(); %> 生成的表单中?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    作为 htmlAttributes 的一部分,例如

    Html.BeginForm(
        action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
    

    或者您可以将null 传递给动作和控制器,以获得与 BeginForm() 相同的默认目标,无需任何参数:

    Html.BeginForm(
        null, null, FormMethod.Post, new { enctype="multipart/form-data"})
    

    【讨论】:

    • 就像一个注释,你可以为动作和控制器传递 null 以获得与不带参数的 BeginForm() 给出的相同的默认目标。
    • @Brad:很棒的评论!将其合并到答案中。
    • 你好,我如何将 enctype 指定为 Shift-JIS,即日文编码格式?
    • 我总是更喜欢指定动作/控制器,因为可以根据您的页面操作来操纵 url,因此让动作/控制器为空可能会导致意外行为。
    【解决方案2】:

    您还可以对强类型版本使用以下语法:

    <% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), 
              FormMethod.Post, 
              new { enctype = "multipart/form-data" })) 
       { %>
    

    【讨论】:

    • 在当前版本 (RC1) 中无法执行此操作。
    • 这是一个巨大的无赖 :( 那么我们该怎么做呢?我们需要另一个 dll 吗?MVC 期货之类的?
    • 是的,确实...我相信所有强类型(基于表达式)的方法都在期货程序集中(aspnet.codeplex.com/Release/…)。
    • @Jason, dp:使用 Nick 的扩展方法,也可以提供这种签名。仍然包括期货当然是更好的方法。
    【解决方案3】:

    我知道这很旧,但如果您需要一遍又一遍地创建该表单,您可以创建一个自定义扩展:

    public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
    {
        return htmlHelper.BeginForm(null, null, FormMethod.Post, 
         new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
    }
    

    使用然后就变成了

    <% using(Html.BeginMultipartForm()) { %>
    

    【讨论】:

      猜你喜欢
      • 2013-07-22
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多