0

I got the following code in the .cshtml file:

<tr>
   <td class="registerWidth"><b>Image:</b></td>
   <td>
      @Html.TextBoxFor(m => m.File, new { type = "file", accept="image/*" })
      @Html.ValidationMessageFor(m => m.File, "", new { @class = "redColor" })
   </td>
</tr>

This is in my ViewModel:

  public Image File { get; set; }

(Image is from System.Drawing)

The problem is, File is null in the Controller every time.

 public ActionResult Contact(ContactViewModel data)
        {
            var Image = data.File //data.File is null
        }

2 Answers2

0

In your ViewModel, you need to change the type from Image to HttpPostedFileBase:

public HttpPostedFileBase File { get; set; }

And your Controller:

[HttpPost]
public ActionResult Contact(ContactViewModel data)
{
   var Image = data.File //data.File is null
}

And your Form should look like:

@Html.Beginform("Contact", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })
Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
0

As you have stated in your comment, you are using Html.Beginform("Contact", "Home", FormMethod.Post

However, can I suggest the following as when posting images to controller methods, it seems to work fine.

 @using ("Contact", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})
 {
     // form things blah blah blag

     // When it comes to inputting the image file, I suggest you do the following
     // Instead of this @Html.TextBoxFor(m => m.File, new { type = "file", accept="image/*" })

    // Have
    <input type="file" name="file" id="fileUpload" accept=".png, .jpg, .jpeg"/>
 }

You controller method would then be the following to reflect these changes.

public ActionResult Contact(ContactViewModel model, HttpPostedFileBase file)
{
    var Image = file.FileName;
}

So what are we doing here?

We are creating a form such as you have done before but we are adding an extra parameter that specifies how the form should be encoded when passing it to the controller.

<input type="file" name="file" id="fileUpload" accept=".png, .jpg, .jpeg"/>

Here we are saying that there will be an input called 'file' that can accept png, jpg or jpeg images.

HttpPostedFileBase file

This is the file that we will be passing. The name has to be the exact same name as the name in the input tags

JamesS
  • 2,167
  • 1
  • 11
  • 29