2017-12-20 4 views
1

보기 코드ASP NET MVC 5 제거 파일

@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> 
} 

컨트롤러

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

가 나는 버튼으로 사진을 삭제하고 싶습니다. 내가 어떻게 해 ? 제품을 삭제할 수는 있지만 사진을 삭제할 수는 없습니다. Id가있는 제품을 삭제할 수 있습니다. 인터넷에서 예제를 만들려고했으나 할 수 없었습니다. 설명을 해보시겠습니까?

+0

데이터베이스 테이블에'ImageName' 컬럼을 만들고'product-name-123'과 같은 이미지 이름을 저장 한 다음 제품 ID를 사용하여 ImageName을 가져 와서 [File.Delete] (https://stackoverflow.com/questions/)를 사용하십시오. 6391711/how-to-delete-a-file-after-checking-that-exists)를 사용하여 이미지를 삭제하십시오. – stom

+0

이해가 안됩니다. 예를들 수 있습니까? 고맙습니다. –

+0

이미지 이름을 폴더에 저장하는 방법을 알 수 있습니까? 이름은 어떻게 생겼습니까? – stom

답변

0

다음은 몇 가지 기본 설정입니다.

작업 방법 :

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

    } 

인덱스보기

@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.