3

I have a problem with update data in Asp.net MVC 5 with Razor Engine . my Update code works fine but I have some problems with it . When I update Image , old image stays in Images folder. I want to delete old image if it changed . and I want to stay old image if it didn't change . How can I do it ? Thanks a lot for any help I don't know how write if statement for this :/

CarouselRepositories.cs

public bool Update(NP1.Models.Carousel entity, bool autoSave = true)
    {
        try
        {

            db.Carousels.Attach(entity);
            db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
            if (autoSave)
                return Convert.ToBoolean(db.SaveChanges());
            else
                return false;
        }
        catch
        {
            return false;
        }
    }

Admin controller

[HttpGet]
    public ActionResult EditCarousel(int id)
    {

        var load = db.Carousels.Find(id);
        return View(load);
    }

    [HttpPost]
    public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
    {
        CarouselRepositories blCarousel = new CarouselRepositories();
        string path = "";
        var fileName = "";
        var rondom = "";
        if (UploadImage != null)
        {

            fileName = Path.GetFileName(UploadImage.FileName);
            rondom = Guid.NewGuid() + fileName;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), rondom);

            carousel.CarouselImage = rondom;
        }
        if (ModelState.IsValid)
        {

            UploadImage.SaveAs(path);
            carousel.CarouselImage = rondom;
            if (blCarousel.Update(carousel))
            {
                return JavaScript("alert('Carousel slide added');");
            }
            else
            {
                return JavaScript("alert('didn't add');");
            }
        }
        else
        {
            return JavaScript("alert('Error');");
        }

    }

EditCarousel.cshtml:

@model NP1.Models.Carousel

@{
ViewBag.Title = "EditCarousel";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}
 @using (Html.BeginForm("EditCarousel", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.CarouselID)
    <div class="form-group">
        @Html.LabelFor(model => model.CarouselSubject, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CarouselSubject)
            @Html.ValidationMessageFor(model => model.CarouselSubject)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CarouselInfo, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CarouselInfo)
            @Html.ValidationMessageFor(model => model.CarouselInfo)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CarouselImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @*@Html.EditorFor(model => model.CarouselImage)*@
            @Html.ImageFor(model => model.CarouselImage, new {width="300"},"","Images","Carousel")
            @Html.Upload("UploadImage")
            @Html.HiddenFor(model => model.CarouselImage)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}

Updated Amin Controller :

 [HttpPost]
    public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
    {
        CarouselRepositories blCarousel = new CarouselRepositories();
        string path = "";
        var fileName = "";
        var rondom = "";
        if (UploadImage != null)
        {

            fileName = Path.GetFileName(UploadImage.FileName);
            rondom = Guid.NewGuid() + fileName;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), rondom);

            carousel.CarouselImage = rondom;
        }
        else
        {
            fileName = carousel.CarouselImage;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), fileName);
        }
        if (ModelState.IsValid)
        {

            UploadImage.SaveAs(path); // I got error in this line 
            carousel.CarouselImage = rondom;
            if (blCarousel.Update(carousel))
            {
                return JavaScript("alert('Carousel slide added');");
            }
            else
            {
                return JavaScript("alert('didn't add');");
            }
        }
        else
        {
            return JavaScript("alert('Error');");
        }

    }
14
  • Do you mean that if UploadImage is not null in the POST method, then you want to delete the existing image? Commented Jan 10, 2016 at 6:33
  • Yes , I want this . but I have another problem too . If UploadImage to be null I get error , I spend 2-3 days but I couldn't fix it . @StephenMuecke Commented Jan 10, 2016 at 6:37
  • Just delete the folder based on the FileName Commented Jan 10, 2016 at 6:41
  • Assuming the property CarouselImage contains the file name of the existing image, then its value will posted back (you have a hidden input for it) so its just a matter of deleting it (using System.IO.File.Delete()) before you call UploadImage.SaveAs(path); (or better, just use the existing file name so its overwritten) Commented Jan 10, 2016 at 6:41
  • And what is the error you get when UploadImage is null? Commented Jan 10, 2016 at 6:42

1 Answer 1

5

Assuming you want to delete the current file if the value of UploadImage is not null in the POST method, then you can use the System.IO.File.Delete method

private const string _ImagesPath = "~/Images/Carousel";

[HttpPost]
public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
{
  if (ModelState.IsValid)
  {
    CarouselRepositories blCarousel = new CarouselRepositories();
    if (UploadImage != null)
    {
      // Delete exiting file
      System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPath), carousel.CarouselImage));
      // Save new file
      string fileName = Guid.NewGuid() + Path.GetFileName(UploadImage.FileName);
      string path = Path.Combine(Server.MapPath(_ImagesPath), fileName);
      UploadImage.SaveAs(path)
      carousel.CarouselImage = fileName;
    }
    if (blCarousel.Update(carousel))
    {
      ....
    }
    else
    {
      ....
    }
  }
  else
  {
    ....
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you , and sorry I get 'System.Web.Mvc.Controller.File(byte[], string)' is a 'method', which is not valid in the given context error in line File.Delete(Path.Combine(Server.MapPath(_ImagesPath)), carousel.CarouselImage);
OK, you need to use System.IO.File.Delete(....) (you have 2 assemblies with classes named File)
I changed it , now it gave me this error Delete takes 2 arguments ! I have 2 arguments why this error occur ?!
No, You have a parenthesis in the wrong place based on you last comment (the double RHS parenthesis should be at the end) - System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPath), carousel.CarouselImage));
Thank you again , that error fixed , but a new error occur! that's amazing . http://localhost:35676/Admin/EditCarousel/28 The resource cannot be found. !! :(
|

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.