146

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

3 Answers 3

262

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"})
Sign up to request clarification or add additional context in comments.

2 Comments

hi, how do i specify enctype as Shift-JIS which is japanese encoding format?
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.
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" })) 
   { %>

4 Comments

Can't do this in the current version (RC1).
Which is a massive bummer :( So how can we do this? do we need another dll? MVC futures or something?
Yes, indeed...I believe all of the strongly typed (expression-based) methods are in the futures assembly (aspnet.codeplex.com/Release/…).
@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.
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()) { %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.