Spitfire Spitfire - 8 months ago 56
C# Question

Update an Image uploaded to SQL Server in ASP.NET MVC 3

I have successfully uploaded an Image on my SQL Server using ASP.NET MVC 3 C#.

Also I have managed to successfully displayed/downloaded that image in the Index view.

However, the problem occurs when in the Edit view of the data,

If the Image has been changed by selecting the file in the view, the new image stores in the DB and everything is okay.

But when the user does not change the image, the value stored in the SQL Server is a null?

How to avoid this.

i.e, if the image is not selected/updated in the edit view, the previously stored image in the database should not be updated to a null value.

Answer Source

The problem is that when the user doesn't change the image the post doesn't contain the image data. You are bluntly updating all the fields in your table and therefore set image field to NULL.

You can either check if you've actually received an image in the post and do not set it to NULL in update statement, or extract the image upload to separate action. It may be even more friendly for the user to have a clearly separated UI for image upload (otherwise they could be confused: if I edit some other fields, will my image disappear? )