1

I have checked various answer for this, but none of them works for me, my code in .cshtml is as follows:

<input type="file" name="PostedNRLFile" />

and then in controller I have

 public JsonResult SaveRecord(NewAuditLetterViewModel viewModel, FormCollection all, string hvalue, HttpPostedFileBase PostedNRLFile)

Which is always null, Please help me in this.

I have already tried few things like creating a property in viewmodel, this is also null. Also used new { enctype = "multipart/form-data", id = "documentForm" } in my beginform tag. Also checked their is only one tag in source.

Ajay
  • 6,418
  • 18
  • 79
  • 130
Kapil Dhawan
  • 101
  • 1
  • 2
  • 11
  • Show the `BeginForm()` code in your view. –  Aug 26 '15 at 06:00
  • @using (Html.BeginForm("SaveRecord", "EditNewAuditLetter", FormMethod.Post, new { enctype = "multipart/form-data"})) – Kapil Dhawan Aug 26 '15 at 06:08
  • You should edit your question! But what you have shown will work fine. I assume you are doing a normal submit and not using ajax? –  Aug 26 '15 at 06:09
  • The fact your method is returning `JsonResult` suggests you are using ajax to post the form, it which case this wont work at all. Edit you question to make it clear what you are actually doing –  Aug 26 '15 at 06:15
  • Thanks, Stephan, I will modify my code as per your suggestion. – Kapil Dhawan Aug 26 '15 at 07:03

3 Answers3

6

You have to add enctype = "multipart/form-data" in form tag.

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, 
                               new { enctype = "multipart/form-data" }))

Try this c# code in controller action

if (Request.Files != null && Request.Files.Count > 0)
{
    HttpPostedFileBase file = Request.Files[0];
    if (file != null && file.ContentLength > 0)
    {
    }
}

You have to retrieve the file.

Ajay
  • 6,418
  • 18
  • 79
  • 130
  • OP has `HttpPostedFileBase PostedNRLFile` as a parameter in the method so `if (Request.Files != null && Request.Files.Count > 0) { ..}` is unnecessary –  Aug 26 '15 at 06:04
1

if you want to use MVC to upload file you need: - create form and have to set tag: enctype = "multipart/form-data" - create input with name same HttpPostedFileBase in controller

hung le
  • 11
  • 1
0

try this one:

var fileCount = Request.Files.Count;
if (fileCount > 0)
{
 for (int i = 0; i < (fileCount); i++)
    { 
        HttpPostedFileBase Yourfile= Request.Files[i] as   HttpPostedFileBase;
        // do whatever with your file
    }
}
Chinh Phan
  • 1,459
  • 19
  • 22
  • If using parameter `HttpPostedFileBase PostedNRLFile` does not work, then this certainly wont. –  Aug 26 '15 at 06:20