1

View 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 want to delete the picture with the button. How can I do it ? I can delete products but I can not delete pictures. I can delete products with Id. I tried to do examples on the internet but I could not. Would you make an illustrative example?

tom clack
  • 191
  • 3
  • 14

1 Answers1

0

Below are some basic setup which should work for you.

Action Methods:

public ActionResult Index()
{

//Adding some dummy product data for example, Usually you will get  real details from DB.

  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);

     //Here you can instead use `ImageName` property to fetch the name from db based 
        on product id and then delete image

     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 View

@model IEnumerable<DemoMvc.Models.Product>

<h2>Product List</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>

Reference.

Shaiju T
  • 6,201
  • 20
  • 104
  • 196