0

I am trying to remove records from database using Entity Framework.

This is the code:

Controller:

[HttpPost]
public ActionResult DeleteProduct(int?id)
{
    Product prd = db.Products.Find(id);
    db.Products.Remove(prd);
    db.SaveChanges();
    return View();
}

View:

<form method="post" enctype="multipart/form-data">
<div class="row ">
     @foreach (var product in Model)
    {
        <div class="col-md-6 col-lg-4 Products">
            <figure class="card card-product mehsul">

                <div class="img-wrap"> <img class="img-fluid mehsulimg" src="@product.PhotoProducts.First().ImageName" alt=""> </div>
                <div class="handhover">

                    <img class="img-fluid" src="@product.PhotoProducts.Last().ImageName" alt="">
                </div>
                <figcaption class="info-wrap">
                    <a href="/Shop/Product/@product.id">@product.ProdName</a>
                    <p class="desc">Some small description goes here</p>

                </figcaption>
                <div class="bottom-wrap">
                    <a href="" class="m-2 btn btn-sm btn-primary float-right">Paylash</a>
                    <a id="DelProd" href="/ProductAd/DeleteProduct/@product.id" class="m-2 btn btn-sm btn-primary float-right">Sil</a>

                    <div class="price-wrap h5">
                        <span class="price-new">$1280</span> <del class="price-old">$1980</del>
                    </div> <!-- price-wrap.// -->
                </div> <!-- bottom-wrap.// -->
            </figure>
        </div> <!-- col // -->

    }
</div>
</form>

But I am getting this error:

Server Error in '/' Application.
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: /ProductAd/DeleteProduct/1

1
  • You have the method marked with HttpPost, but the a tag does an HttpGet. Commented May 11, 2020 at 18:41

2 Answers 2

1

If You are sending a delete request, it is not a [HTTPPost] and you are passing the whole model to the controller not only the key, so if you need to add id in your request, you should do something like this.

API Version:

[HttpDelete("{id}")]
public ActionResult DeleteProduct(int?id)
{
    Product prd = db.Products.Find(id);
    db.Products.Remove(prd);
    db.SaveChanges();
    return View();
}

Or using something like this for MVC Version with full model

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(YourViewModel viewModel)
{
    var id = viewModel.id;

    Product prd = db.Products.Find(id);
    db.Products.Remove(prd);
    db.SaveChanges();
    return View();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. but i changed <a> to <button> it worked. but now it shows this eror: The DELETE statement conflicted with the REFERENCE constraint "FK_PhotoProduct_Products".
Your welcome, You should remove the linked reference first, for example if you have a picture that is connected to this product by id, you should delete that picture from the database first. Good luck
1

Since your action has the "HttpPost" attribute, you need to do an HTTP POST. Your a tag would only do a GET, and the server would reject it as a page not found. Assuming everything else is correct, then I think it would be something more like this:

<div class="row ">
  @foreach (var product in Model)
  {
    <div class="col-md-6 col-lg-4 Products">
      <figure class="card card-product mehsul">
        <div class="img-wrap"> <img class="img-fluid mehsulimg" src="@product.PhotoProducts.First().ImageName" alt=""> </div>
        <div class="handhover">

          <img class="img-fluid" src="@product.PhotoProducts.Last().ImageName" alt="">
        </div>
        <figcaption class="info-wrap">
          <a href="/Shop/Product/@product.id">@product.ProdName</a>
          <p class="desc">Some small description goes here</p>
        </figcaption>
        <div class="bottom-wrap">
          <a href="" class="m-2 btn btn-sm btn-primary float-right">Paylash</a>
          <form method="post" action="@Url.Action("DeleteProduct","ProductAd", new {id=productid})">
            <button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
          </form>
          // or
          @using(Html.BeginForm("DeleteProduct","ProductAd",new {id=product.id}))
          {
            <button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
          }

          <div class="price-wrap h5">
            <span class="price-new">$1280</span> 
            <del class="price-old">$1980</del>
          </div> <!-- price-wrap.// -->
        </div> <!-- bottom-wrap.// -->
      </figure>
    </div> <!-- col // -->
  }
</div>

4 Comments

Thank you for answer, i used this code and it worked, but now it shows another error:The DELETE statement conflicted with the REFERENCE constraint "FK_PhotoProduct_Products".
That means you have photos of the product you want to delete, and you can't delete the product until you delete the photos associated with that product. Probably something like: foreach(var photo in prd.Photos) db.Photos.Remove(photo); and put that before your db.SaveChanges(), or update your EF model so that it knows about the database constraint you have there.
It works with this code: List<PhotoProduct> list = (from rec in db.PhotoProducts join prod in db.Products on rec.ProductId equals prod.id where rec.ProductId == id select rec).ToList(); foreach (PhotoProduct pht in list) { db.PhotoProducts.Remove(pht);}
Sounds like your EF model could really use some work. Your product should have a property which I'll call "Photos" which gets you access to all the photos for that product. Once you have this mapped correctly in EF, your original query should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.