0

I have a form it's creating by script in jquery plugin like this.

elem.insertHtml('<form method="post" action="Home/ContactUs" enctype="mutlipart/form-data"><input type="file" name="file" id="fileUpload"></form></div>')

I must upload a file, and save it in some folder. When I choose a file, and submit form, on form subbmiting calling the ContactUs action.There is ContactUs action from Home controller.

public ActionResult ContactUs(HttpPostedFileBase file, ContactFormModel model)
{
    //other code
}

But HttpPostedFileBase file is null, and I havn't got any notions why. Can you help me, please?

When I create my form usin Html.BeginForm, it works correctly, by but script there is a problem.

dotNet_d19
  • 43
  • 2
  • 6

4 Answers4

2

You can use 'File' method for uploading file and retrieve them. create a folder in your project something likes 'FileUploads' and then upload File in there. I give you a link where you can see full implementation :- Upload,Save and Retrieve Image from database by using their Id in Code First Method

Community
  • 1
  • 1
mgsdew
  • 729
  • 1
  • 8
  • 27
1

Create HTML form from like this:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="text" name="Subject"/>
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

Also make sure in your Controller, the Method has an attribute [HttpPost] like this:

[HttpPost]
public ActionResult ContactUs(HttpPostedFileBase file, ContactFormModel model)
{
    //other code
}
Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
0

Maybe your model binding is not working in your code. It is your view strongly typed?

Try it whith this answer. https://stackoverflow.com/a/8551621/2664142

Community
  • 1
  • 1
0

Could you change from

elem.insertHtml('<form method="post" action="Home/ContactUs" enctype="mutlipart/form-data"><input type="file" name="file" id="fileUpload"></form></div>')

To

elem.insertHtml('<form method="post" action="Home/ContactUs" enctype="multipart/form-data"><input type="file" name="file" id="fileUpload"></form></div>')

Could you check Request.Files.Count it must be more than 0 if not could you comment me please

 public ActionResult ContactUs(ContactFormModel model)
 {
    Request.Files[0].SaveAs(Server.MapPath(@"~\files\test.jpg"));
    return View();
 }
İbrahim Özbölük
  • 3,162
  • 23
  • 20