Removing Files from an ASP.NET MVC 5 Website

Check Out the Code

@using(Html.BeginForm("Edit",
    "Products",
    FormMethod.Post,
    new {
        enctype = "multipart/form-data"
    })) {
    @Html.AntiForgeryToken()

    < div class = "form-horizontal" >

        @Html.ValidationSummary(true, "", new {
            @class = "text-danger"
        })
    @Html.HiddenFor(model => model.Id)

    < div class = "form-group" >
        @Html.LabelFor(model => model.Image, htmlAttributes: new {
            @class = "control-label col-md-2"
        }) < div class = "col-md-10" >
        < img src = "@Url.Content(Model.Image)"
    width = "150" / >
        < /div> < /div>
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product, HttpPostedFileBase file) {
 if (ModelState.IsValid) {
  Product p = new Product {
   Id = product.Id,
    Name = product.Name,
    Description = product.Description,
    Image = product.Image
  };

  if (file != null) {
   string Image = Path.Combine(Server.MapPath("~/Upload"), Path.GetFileName(file.FileName));
   file.SaveAs(Image);
   p.Image = "~/Upload/" + file.FileName;
  }

  db.Entry(p).State = EntityState.Modified;
  db.SaveChanges();
  return RedirectToAction("Index");
 } else {
  return View(product);
 }

}

public ActionResult Edit(int ? id) {
 if (id == null) {
  return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
 }
 Product product = db.Products.Find(id);
 if (product == null) {
  return HttpNotFound();
 }
 return View(product);
}

I would like to remove the image with a button. How do I achieve this? While I can delete products using their IDs, I'm having trouble deleting images. Although I've tried following examples from online resources, I haven't been successful. Could you provide an illustrative example for me?

Answer №1

Here are some essential steps for setting up your application:

Action Processes:

public ActionResult Index()
{

//Adding sample product data for demonstration purposes, actual details will come from a database query.

  List<Product> products = new List<Product>();

    Product product1 = new Product()
    {
       Id = 1,
       Name = "Bint Beef",
       Description = "Product Bint Beef",
       ImageName = "bintbeef-1"
    };

    Product product2 = new Product()
    {
       Id = 2,
       Name = "Bint Beef 2",
       Description = "Product Bint Beef 2",
       ImageName = "bintbeef-2"
    };

     products.Add(product1);
     products.Add(product2);

     return View(products);
    }



[HttpPost]
public ActionResult DeleteProductImage(int productID)
{
    try
    {
      string file_name = Convert.ToString(productID);

     //Instead of using `file_name`, consider fetching image name based on the product ID from the database and then proceed with image deletion

     string path = Server.MapPath("~/Content/Images/" + file_name + ".jpg");
     FileInfo file = new FileInfo(path);
     if (file.Exists)//check file exsit or not
     {
         file.Delete();
     }

     return Json(new { status = true }, JsonRequestBehavior.AllowGet);
     }

     catch
     {
     return Json(new { status = false }, JsonRequestBehavior.AllowGet);
     }

    }

Index Display

@model IEnumerable<DemoMvc.Models.Product>

<h2>List of Products</h2>


<table class="table">
    <tr>

        <th>
            Product Id
        </th>
        <th>
            Name
        </th>

        <th>
            Image Name
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <th>
                @item.Id
            </th>
            <td>
                @item.Name
            </td>

            <td>
                @item.ImageName
            </td>

            <td>

             @using (Html.BeginForm("DeleteProductImage", "Home"))
             {

                <input name="productID" type="hidden" value="@item.Id" />

                <button type="submit">Delete Image</button>
             }

            </td>
        </tr>
    }

</table>

Resource.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to turning off tab discarding in Google Chrome with JavaScript

Is there a way to prevent Chrome from discarding tabs on chrome://discards/ using JavaScript so that the tab remains open even after closing the page or browser? I am aware that this can be achieved with an extension, but I am interested in creating my o ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

While attempting to use $scope.$apply() in Angular, I encountered a bug that

I have set up a specific example in a jsbin: http://jsbin.com/deqerelita/1/ Situation The concept is quite straightforward. You click a button, the controller adds to the model, and the view updates accordingly with a hidden input type="file". After the v ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

Having trouble with Selenium WebDriverJS on both FireFox and Internet Explorer

Having developed multiple JavaScript tests using chromedriver to run them in Chrome, I am now facing the challenge of running these same tests in FireFox and IE. The test below is functional in Chrome: var assert = require('assert'), test = requ ...

Troubleshooting: Inconsistencies with AngularJS' ngmaxlength and ng-required

Input Type <div class="form-group" ng-class="{ 'has-error': loginForm.password.$dirty && loginForm.password.$error.required }"> <label for="password">{{ 'PASSWORD' | translate }} <span class="required-field"& ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

Utilizing the information from a file as the data for an object

I'm struggling to incorporate data from a .json file using formData in an HTTP request. I'm having trouble adding this data into the options object correctly. {"name":"charlie","age":"20"} Here is what I ...

How can you define the HTTP method when using AWS Lambda.invoke() in JavaScript?

Referencing the AWS documentation: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property var params = { FunctionName: 'STRING_VALUE', /* required */ ClientContext: 'STRING_VALUE', InvocationType: E ...

Troubles with ASP.NET Timeouts

Currently, I am dealing with an older system and have found some timeout values specified in the web.config file. <sessionState timeout="120" /> ... <forms name="login" timeout="240" /> In order to prevent any possible issues related to Null ...

Obtain an item from an array by utilizing the property with Lodash _.find

I currently have an array of objects called memberToChange.checkboxes: ICheckbox[] structured like this: https://i.stack.imgur.com/LyKVv.png Within this setup, there is also a variable named internalNumber with the value "3419". My objective is to locate ...

Modify the hue of the div as soon as a button on a separate webpage is

Looking for assistance with a page called "diagnosticoST" that contains four buttons (btn-institucional, btn-economico, btn-social, btn-natural). These buttons have different background colors until the survey inside them is completed. Once the user comple ...

Generating a unique element with a specified identification number through JavaScript

Every time the button is clicked, I want to generate a new element with specific id names. Specifically, I am building a form that includes: <h2>Ownership Structure</h2> <div class="form-outline mb-4"> <input type="text" id="ownerNam ...

Execute a javascript function using dynamic calling

I have defined several functions inside an array structure as shown below. checkInputType : function(sel){ alert($(sel).prop('type')); }, checkSelect : function(el){ ....... }, ..... These functions can be called like options.checkInput($(thi ...

Open window maximizing size

URL = "window.open('../GBY/Reports/ReportViewer.aspx?ReportParams=" + ReportParams + "&ReportName=" + ReportName + " ' , '_blank');"; ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), "OPEN_WINDOW ...

The function $.ajax(...) is not defined

Even when using the standard version of jQuery, I still encounter the issue. <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"& ...

Adjust size of element in relation to Background Cover using jQuery

Can you help me solve a challenge I'm facing? I have a website with a fullsize background image, and I need to attach a div to a specific position on the image while ensuring that it scales in the same way as the background image with the "background ...

Creating buttons in ASP.NET can be accomplished by utilizing the Response.Write() method

Currently in the process of developing an <asp:Button> in ASP.Net. The code I currently have is as follows: <b>Tags: <% List<string> tags = GetTags(); foreach(string tag in tags) { Respons ...

Construct a table from JSON data

I am having trouble generating a table from JSON data. It seems like there may be an issue with my link, but there could be something else going on as well. I am not seeing any data displayed in my table and the error message I am getting is: Cannot read ...