0

I have this model:

public class PostAddRequest
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string FeaturedImagePath { get; set; }
        public HttpPostedFileBase FeaturedImage { get; set; }
    }

Now, in the controller I cannot find how to populate the HttpPostedFileBase property, so that the input type field would be populated.

3
  • This doesn't make much sense though. A file input is for the user to select a file on their own file system. What would be the purpose of pre-populating it with a file from the server? (Which the browser doesn't have any way of doing, precisely because it doesn't make sense...) Commented Jun 23, 2022 at 15:22
  • @David because I want to have an edit functionality, so the user would be able to preview the previous image and if he decides to just submit the form without changes, the input would be already populated and not return a null property. Commented Jun 23, 2022 at 15:23
  • @David In the edit view, the input type file is not populated, so it just deletes the image from the database if the user doesnt add a new image and saves the form. Commented Jun 23, 2022 at 15:26

1 Answer 1

2

This can't be done, because it shouldn't be done. Change your approach.

You don't want to pre-populate a file input from the server. Even if it were possible, consider what would be involved in a scenario where the user submits the form without changing the file:

  • The server would send the entire file to the client
  • The client would save the file to the file system
  • The client would re-send the entire file back to the server
  • The file would still be saved somewhere on the client for no reason? What then?

Take a step back and re-think the approach. The file input is initially empty and there for the purpose of the user selecting a new file if they want to.

To show the user that a file already exists on the server, provide a UI separate from the file input. It could be something as simple as this:

<a href="/files/123">Filename.ext</a> (click to download)
<a href="/files/123/delete">Delete?</a>
Select a new file: <input type="file" name="file" />

Or anything along those lines of functionality. Basically you have three operations available:

  • Get the file
  • Delete the file
  • Upload a new file

Those are separate operations, invoked by separate UI elements. The file input only covers one of those operations.

Sign up to request clarification or add additional context in comments.

1 Comment

ah, I think I'll just display the current image as a <img> and check if it is null or not in the backend so I can replace it. Thanks for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.