0

I'm trying to add upload a file field inside my Views. I edited my ViewModel and added below line to it: public HttpPostedFileBase ImageUrl { get; set; } Then I added below helper for file upload:

        @Html.EditorFor(model => model.ImageUrl)

I also changed my form helper like this:

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

However it shows internal fields of file when I run my view:

enter image description here

What I have missed that lead to this situation?

VSB
  • 9,825
  • 16
  • 72
  • 145

2 Answers2

0

Use the TextBoxFor helper method.

@using (Html.BeginForm("Create", "Home", FormMethod.Post,
                                          new { enctype = "multipart/form-data" })) 
{
   @Html.TextBoxFor(s=>s.ImageUrl,new { type="file"})
   <input type="submit" />
}

Or even pure HTML

@using (Html.BeginForm("Create", "Home", FormMethod.Post,
                                                 new { enctype = "multipart/form-data" })) 
{
   <input type="file" name="ImageUrl" />
   <input type="submit" />
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I don't know why this will return null in my ViewModel? my httppost controller looks like this `public ActionResult Create(ViewModelCreate viewModel)` and viewModel.ImageUrl is null. – VSB May 09 '16 at 09:56
0

Make sure your ImageUrl property on your model object looks as follows:

[DataType(DataType.Upload)]
public HttpPostedFileBase ImageUrl { get; set; }

And then, in your view, just use the editorfor HTML helper as per normal

@Html.EditorFor(m => m.ImageUrl)
CShark
  • 2,183
  • 1
  • 24
  • 42