archie
archie

Reputation: 179

file upload doesn't work in ASP.NET MVC4 - mobile template

I am using C# and ASP.NET MVC4 for a web application (mobile template).

Now I have the following code in my view:

     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
     { 
     <label for="file">Upload:</label>
     <input type="file" name="file" id="file"/>
     <input type="submit" value="Upload" />
     }

and this in my controller:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string path = System.IO.Path.Combine(Server.MapPath("~/Content"), System.IO.Path.GetFileName(file.FileName));
        file.SaveAs(path);
        ViewBag.Message = "File uploaded successfully";
        return View();
    }

when I run the application and try to upload a file, I get "Object reference not set to an instance of an object." message in Visual Studio. But I know that the code above works fine in ASP.NET MVC3 as I've used it before.

Can anyone help me with this?

Upvotes: 3

Views: 2585

Answers (2)

MisterIsaak
MisterIsaak

Reputation: 3922

Add this attribute to your form: data-ajax="false"

@using(Html.BeginForm("Index", "Home", FormMethod.Post,  new { enctype="multipart/form-data", data_ajax="false"})){
     <label for="file">Upload:</label>
     <input type="file" name="file" id="file"/>
     <input type="submit" value="Upload" />
}

Upvotes: 3

Artless
Artless

Reputation: 4568

You don't have to use HttpPostedFileBase, as the matter of fact you don't have to receive any parameters in your [HttpPost] Action. You can get your file from the request like this as long as your form is set to enctype = "multipart/form-data" (which you already do):

var file = Request.Files[0];

Upvotes: 1

Related Questions