0

I have been mostly following this tutorial: http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

It created a good create view that allows the user to upload an image.

How would I create a similar page that displays the current image file (such as what this shows when the user has selected one in the create view) and still allows the user to select a different image?

@model ImageViewModel

<form action="" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Name:
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        Image Upload:
        @Html.TextBoxFor(model => model.ImageUpload, new { type = "file" })
    </div>
    <button type="submit">Edit</button>
</form>



public class ImageViewModel
{
    public string Name { get; set; }
    public HttpPostedFileBase ImageUpload { get; set; }
}

As it currently is, this just allows the Name to be changed and a new image to be uploaded. I want it to show the filename of the current image, but I don't know of a way to upload info to the HttpPostedFileBase attribute (database is currently holding the filename/path from create).

Any thoughts would be appreciated. Thanks.

NerdyFool
  • 531
  • 1
  • 7
  • 14
  • It's not clear to me what you're asking. It sounds like you're asking how to pre-populate the file input on page load with the name of the existing uploaded file? Most browsers ignore the value field on file inputs so that won't make much sense. – Justin Helgerson Oct 23 '14 at 00:48
  • Another odd bug from not being able to repopulate ImageUpload is that it gets cleared and must be reselected if the ModelState was invalid. I just feel there should be a better way to handle this situation. – NerdyFool Oct 23 '14 at 17:41

1 Answers1

2

Add an extra property to your ImageViewModel and bind the current filename to that property:

public class ImageViewModel
{
    public string Name { get; set; }

    public string FileName { get; set; }

    public HttpPostedFileBase ImageUpload { get; set; }
}

In your Edit View just display the FileName property:

@model ImageViewModel

<form action="" method="post" enctype="multipart/form-data">

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div>
        Name:
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        Current uploaded file:
        @Html.DisplayFor(model => model.FileName)
    </div>
    <div>
        Image Upload:
        @Html.TextBoxFor(m => m.ImageUpload, new { type = "file", value = "test" })
    </div>
    <button type="submit">Save</button>

</form>
Tom Kluskens
  • 166
  • 3
  • This is what I ended up doing. I was hoping I could just prepopulate ImageUpload. With the other EditorFor, TextBoxFor, etc, they show the data that is prepopulated into them. I was hoping for a solution that would accomplish this with ImageUpload as well. – NerdyFool Oct 23 '14 at 16:04