Reputation: 133
I'm working with an MVC5 project, I have created a simple system that the user can upload a file "CV" for each Employee. Now all thing work for me fine except "DELETING File". I need to add action method for deleting uploaded file and the ability to replace it with another file.
in the model class I have created two property HttpPostedFileBase CV to save the uploaded file and String cvName, to save the file name and use it to create a link to that file.
In the controller that what I have done:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteCV(string cvName)
{
//Session["DeleteSuccess"] = "No";
var CVName = "";
CVName = cvName;
string fullPath = Request.MapPath("~/Content/CVs/" + CVName);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
//Session["DeleteSuccess"] = "Yes";
}
return RedirectToAction("Index");
}
and this is the view:
<div class="form-group">
@Html.LabelFor(model => model.CV, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@{
if (File.Exists(Server.MapPath("~/Content/CVs/"
+ Html.DisplayFor(model => model.cvName))))
{
<a href="~/Content/CVs/@Html.DisplayFor(model => model.cvName)"> @Html.DisplayFor(model => model.cvName) @Html.HiddenFor(model => model.cvName)</a>
<a href="@Url.Action("DeleteCV", new { @Model.cvName })">
<img src="@Url.Content("~/Content/Images/Delete.jpg")" width="20" height="20" class="img-rounded" />
</a>
}
else
{
<input type="file" name="file" accept="pdf" />
}
}
</div>
</div>
I can't delete the file, each time this message appears
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /DeleteCV
Upvotes: 1
Views: 2949
Reputation:
You're sending a GET
to a POST
Change the [HttpPost]
to [HttpGet]
Or use JQuery and send a DELETE
verb like I mentioned in the comments
Upvotes: 7
Reputation: 151674
You're using an <a href="@Url.Action("DeleteCV", new { @Model.cvName })"></a>
, so your link will become /Controller/DeleteCV?cvName=SomeName
, which will be executed as GET. You don't want that for many reasons, and frankly, the rest of the code is a mess too. Don't do business logic (like checking for a file) in your view, and you might want to add a few checks around that File.Delete()
.
Do the file check in your controller, saving the result in a model variable, and create a separate form to POST to your Delete method:
if (@Model.FileExists)
{
@using(Html.BeginForm("Cv", "DeleteCV", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.cvName)
<input type="submit" value="Delete" />
}
}
else
{
@using(Html.BeginForm("Cv", "UploadCV", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="file" name="file" accept="pdf" />
<input type="submit" value="Upload" />
}
}
Upvotes: 1