Html.BeginForm and adding properties

asp.net Mvc

asp.net Mvc Problem Overview


How would I go about adding enctype="multipart/form-data" to a form that is generated by using <% Html.BeginForm(); %>?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

As part of htmlAttributes,e.g.

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

Or you can pass null for action and controller to get the same default target as for BeginForm() without any parameters:

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

Solution 2 - asp.net Mvc

You can also use the following syntax for the strongly typed version:

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

Solution 3 - asp.net Mvc

I know this is old but you could create a custom extension if you needed to create that form over and over:

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

Usage then just becomes

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevinUKView Question on Stackoverflow
Solution 1 - asp.net Mvcliggett78View Answer on Stackoverflow
Solution 2 - asp.net Mvcdp.View Answer on Stackoverflow
Solution 3 - asp.net MvcNick OlsenView Answer on Stackoverflow