views:

2198

answers:

6

In the View page, code is below:

<% =Html.BeginForm("About", "Home", FormMethod.Post, new {enctype="multipart/form-data "})%>
<input type ="file"  name ="postedFile" />
<input type ="submit"  name ="upload" value ="Upload" />
<% Html.EndForm(); %>

In the Controller, something like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult  About(HttpPostedFile postedFile)
{
//but postedFile is null 
View();
}

But postedFile is null, how to do it?

+3  A: 

This doesn't answer why your parameter is null, but you can dig into the request directly. This might not be the most "MVC" way of doing this though. try this in your method body:

var upload = Request.Files["postedFile"]
if (upload.ContentLength > 0)
{
  // Do whatever
}

To be more "MVC, "You could pull that code out of your controller into an IModelBinder implementation and using a custom object as a parameter to your method. This Scott Hanselman blog post shows the steps to implement a custom ModelBinder.

Ben Robbins
A: 

I also get some quirks with <%= Html.BeginForm ...%>. So, I use the using. Again, on the Controller side, I just grab my uploaded files form the request object.

Try this. It works:

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

    <input type="file" id="postedFile" name="PostedFile" />
    <input type="submit" />

<%
}

%>

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Post(FormCollection form)
    {
      HttpPostedFileBase postedFile =   Request.Files["PostedFile"];
        return RedirectToAction("Index");
    }
Pita.O
the postedFile is still null
Just copy and paste my controller action and view. It works for me. Note that my action method is not taking HttpPostedFile as argument.
Pita.O
+2  A: 

checkout Scott Hansleman's blog entry

Matthew
+1  A: 

Which version of MVC are you using? Right now with the RC candidate I tried using HttpPostedFile and I got an "does not have a blank constructor error." I had to use HttpPostedFileBase.

More importantly though, is the version of MVC you're running on, depending on the version, how your retrieve a posted file will be different.

Min
+3  A: 

Use HttpPostedFileBase and also name the parameter exactly as in the form. eg. if you have

<input type="file" id="file1" name="file1" />

you have to have the method head:

public ActionResult About(HttpPostedFileBase file1)
Carl Hörberg
And id and name need to be the same right?
cottsak
actually only the name is mandatory (and has to conform to the method parameters name). The id is only used by javascript and css (simplified).
Carl Hörberg
A: 

I had the same problem:

You have to define a name AND id for the input element:

<input type ="file"  name ="postedFile" id="postedFileId"  /> 

Best regards

Stefan

Ghecco