c# - Edit and display entity images -
i want able replace old images new. got 1 many relationship between entites -> many images 1 product.
if change images, old staying in database. never used. after time database able make huge itself. how delete these old files ?
public actionresult edit(int? id) { if (id == null) { return new httpstatuscoderesult(httpstatuscode.badrequest); } product product = db.products.include(p => p.filepaths).where(i => i.productid == id).single(); if (product == null) { return httpnotfound(); } return view(product); } [httppost] public actionresult edit(int id, ienumerable<httppostedfilebase> uploads) { var product = db.products.include(p => p.filepaths).where(p => p.productid == id).single(); if (modelstate.isvalid) { try { product.filepaths = new list<filepath>(); foreach (var upload in uploads) { if (upload != null && upload.contentlength > 0) { var photo = new filepath { filename = path.getfilename(upload.filename), filetype = filetype.photo }; product.filepaths.add(photo); upload.saveas(path.combine(server.mappath("~/content/images"), photo.filename)); } } db.entry(product).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } catch (retrylimitexceededexception) { modelstate.addmodelerror("", "unable save changes. contact administrator."); } } return view(product); }
my view edit() is:
@model domain.entities.product @using (html.beginform("edit", "home", formmethod.post, new { enctype = "multipart/form-data" })) { // code ommited brevity.. <div class="row"> @html.label("images:", new { @class = "control-label col-md-2" }) <div class="col-md-1"> <input type="file" name="uploads" id="upload1" /> </div> <div class="col-md-offset-2 col-md-1"> <input type="file" name="uploads" id="upload2" /> </div> <div class="col-md-offset-2 col-md-1"> <input type="file" name="uploads" id="upload3" /> </div> </div> //code ommited brevity..
also if tell me how change grateful.
i getting first image of product many times many images product got. want display images once. in trouble directory images.
<div class="row"> <label class="control-label col-md-2"> obecne zdjęcia:</label> @foreach (var item in model.filepaths) { <div class="col-md-offset-1 col-md-1"> <img src="~/content/images/@model.filepaths.firstordefault(f => f.filetype == filetype.photo).filename" alt="" style="width:auto; height:100px"> </div> } </div>
my model class filepath:
public class filepath { public int filepathid { get; set; } public string filename { get; set; } public filetype filetype { get; set; } public int? productid { get; set; } //navigation.. public virtual product product { get; set; } }
every appreciated. thanks!
Comments
Post a Comment