File upload not working in ASP.NET MVC4 - mobile pattern

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

Now I have the following code in my opinion:

     @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 is 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 my application and try to download a file i get "Object reference not set in object instance." post in Visual Studio. But I know that the code above works fine in ASP.NET MVC3 as I have used it before.

Can anyone help me with this?

+3


source to share


2 answers


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" />
}

      

+3


source


You don't need to use HttpPostedFileBase

as you don't need to receive any parameters in your [HttpPost] action. You can get your file from request like this if your form is set to enctype = "multipart/form-data"

(which you already do):



var file = Request.Files[0];

      

+1


source







All Articles