Reputation: 1031
I have an Edit View so to edit my records. One of the fields is a file. May I change the value of "Chose a file" with the name of the file?
I have try this but it doesn't work
@Html.EditorFor(model => model.file, new { htmlAttributes = new {@class = "form-control", type="file" name = "file", @Value = Model.file} })
I need that because the file name is going to null when I save the record from Edit View.
thank you
Upvotes: 0
Views: 601
Reputation: 239290
For security reasons, a file input cannot be set with a value. The user must choose a file from their filesystem to set the value.
You should use a view model with a propert of HttpPostedFileBase
to hold the file upload, and in your post action conditionally only overwrite the value on your entity if that property has a value.
If you need the field to be required, then you must either remove the error on post if the entity already has an upload or manually require it only in your create action.
Remove the error (assuming you're using [Required]
on the property):
if (entity.file != null)
{
ModelState["file"].Errors.Clear();
}
Conditionally require (don't use [Required]
on the property and instead in your create action:
if (model.file == null || model.file.ContentLength == 0)
{
ModelState.AddModelError("file", "You must upload a file");
}
Upvotes: 1