Rehan Khan Rehan Khan - 7 months ago 68
Javascript Question

Display FileName with fileUpload on Edit if file exists in a folder and filename in database in ASP.NET MVC

On Edit, how to assign filename (stored in SQL database as a string) to fileupload control.

Controller

public ActionResult editLeaveRequest(int id)
{
var model = hc.leaveRequests.Find(id);
if (!String.IsNullOrEmpty(model.documentUrl))
{
model.documentUpload.FileName = model.fName;
}
return View(model);
}


I've saved file in a folder and its
filename(fName)
in SQL database as string. What I'm trying to do is, check if
filename(fName)
exists in the database, if so, assign it to
fileUpload
's fileName and pass this model to ViewPage.

What I want is, display filename with the fileupload control as its status to inform user that there is a file already attached to this record and its filename is equal to
filename(fName)
. But above code is giving following error:


Property or Indexer 'HttpPostedFileBased.FileName' cannot be assigned to -- it is read only`


Can someone please suggest how to accomplish it?

Answer

You should live with the fact that every time you reload your page, file upload input will be empty. What you need to do is:

  • Somehow show that the file exists, but in a separate block (e.g. <div>MyFile.png</div>)
  • Add file delete functionality as needed or do your model.documentUpload check to see if new file was posted and if it was, replace existing file with the new one.
  • Validate your form submit on the server-side to allow only one file per your entity.

enter image description here