How would I go about adding enctype="multipart/form-data" to a form that is generated by using <% Html.BeginForm(); %>?
Asked
Active
Viewed 1.3e+01k times
143
Konrad Rudolph
- 506,650
- 124
- 909
- 1,183
KevinUK
- 5,003
- 4
- 30
- 46
3 Answers
257
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"})
chiccodoro
- 14,059
- 17
- 86
- 129
liggett78
- 11,158
- 2
- 28
- 28
-
45Just as a note, you can pass null for action and controller to get the same default target that BeginForm() without parameters gives. – Brad Robinson Sep 13 '10 at 13:26
-
2@Brad: Great comment! Incorporated it into the anwer. – chiccodoro Oct 21 '11 at 11:15
-
hi, how do i specify enctype as Shift-JIS which is japanese encoding format? – Govind Jun 30 '14 at 16:02
-
I always prefer to specify the action / controller, because the url can be manipulated depending on what you page do, so letting action / controller on null may cause unexpected behaviors. – César León Mar 08 '17 at 20:26
19
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" }))
{ %>
Pure.Krome
- 82,011
- 105
- 379
- 615
dp.
- 7,958
- 7
- 32
- 28
-
1
-
Which is a massive bummer :( So how can we do this? do we need another dll? MVC futures or something? – Pure.Krome Apr 25 '09 at 01:35
-
4Yes, indeed...I believe all of the strongly typed (expression-based) methods are in the futures assembly (http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471). – dp. Apr 25 '09 at 08:50
-
@Jason, dp: Using Nick's extension method, it would be possible to provide that kind of signature, too. Still including futures is certainly a better approach. – chiccodoro Oct 21 '11 at 11:19
13
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()) { %>
SteveC
- 14,716
- 23
- 93
- 165
Nick Olsen
- 6,241
- 9
- 52
- 74