-1

I want to upload images for gallery and Main page in my website , so I upload image to file system and save info abvout images in db , I use one to many relationship in database and also I use View Model. All data updates in database without problem , I checked it, but I can't display Images in View , maybe I have to write something else in my method Edit?? Please explain me. So Here is my code: View Models

public class FurnitureVM
{
    public FurnitureVM()
    {
        this.MainImage = new ImageVM();
        this.SecondaryImages = new List<ImageVM>();
    }

    public int? ID { get; set; }
    [Display(Name = "Name")]
    [Required(ErrorMessage = "Enter name")]
    public string Name { get; set; }

    [DataType(DataType.MultilineText)]
    [Display(Name = "...")]
    [Required(ErrorMessage = "...")]
    public string Description { get; set; }
    [Display(Name = "Price ()")]
    [Required]
    [Range(0.01, double.MaxValue, ErrorMessage = "...")]
    public decimal Price { get; set; }

    [Display(Name = "...")]
    [Required(ErrorMessage = "...")]
    public string Manufacturer { get; set; }
    [Display(Name = "Size")]
    [Required(ErrorMessage = "...")]
    public string Size { get; set; }

    [Display(Name = "....")]
    [Required]
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    public IEnumerable<SelectListItem> CategoryList { get; set; }
    public HttpPostedFileBase MainFile { get; set; }
    public IEnumerable<HttpPostedFileBase> SecondaryFiles { get; set; }
    public ImageVM MainImage { get; set; }
    public List<ImageVM> SecondaryImages { get; set; }
}
public class ImageVM
{
    public int? ID { get; set; }
    public string Path { get; set; }
    public string DisplayName { get; set; }           
}

My method in controller:

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var furniture = db.Furnitures.Find(id);
    if (furniture == null)
    {
        return HttpNotFound();
    }

    FurnitureImages main = furniture.Images.Where(x => x.IsMainImage).FirstOrDefault();

        FurnitureVM model = new FurnitureVM();
        model.Name = furniture.Name;
        model.Description = furniture.Description;
        model.Price = furniture.Price;
        model.Size = furniture.Size;
        model.CategoryId = furniture.CategoryId;
         model.Manufacturer = furniture.Manufacturer;
        model.MainImage.Id = main.Id;
        model.MainImage.DisplayName = main.DisplayName;
        model.MainImage.Path = main.Path;
        model.MainImage.IsMainImage = main.IsMainImage;

    //ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", furniture.CategoryId);
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FurnitureVM model)
{
    if (model.MainFile != null && model.MainFile.ContentLength > 0)
    {
        string displayName = model.MainFile.FileName;
        string extension = Path.GetExtension(displayName);
        string fileName = string.Format("{0}.{1}", Guid.NewGuid(), extension);
        string path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
        model.MainFile.SaveAs(path);
        model.MainImage = new ImageVM() { Path = path, DisplayName = displayName };
    }

    foreach (HttpPostedFileBase file in model.SecondaryFiles)
    {
        FurnitureImages images = new FurnitureImages
        {
            //This is for secondary images for gallery  
        };
    }

    if (!ModelState.IsValid)
    {
        model.CategoryList = new SelectList(db.Categories, "CategoryId", "Name",model.CategoryId); // repopulate the SelectList
        return View(model);
    }

    Furniture furniture = db.Furnitures.Where(x => x.FurnitureId == model.ID).FirstOrDefault();
        FurnitureImages main = furniture.Images.Where(x => x.IsMainImage).FirstOrDefault();
        furniture.Name = model.Name;
        furniture.Description = model.Description;
        furniture.Manufacturer = model.Manufacturer;
        furniture.Price = model.Price;
        furniture.CategoryId = model.CategoryId;
        furniture.Size = model.Size;
        main.Id = model.ID;
        main.DisplayName = model.MainImage.DisplayName;
        main.Path = model.MainImage.Path;
        main.IsMainImage = model.MainImage.IsMainImage;


    if (model.MainImage != null && !model.MainImage.ID.HasValue)
    {
        FurnitureImages image = new FurnitureImages
        {
            Path = model.MainImage.Path,
            DisplayName = model.MainImage.DisplayName,
            IsMainImage = true
        };
        furniture.Images.Add(image);
    }

    // ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", furniture.CategoryId);
    db.Entry(furniture).State = EntityState.Modified;
    db.SaveChanges();
     return RedirectToAction("Index");
}

And part of my view

@model FurnitureStore.ModelView.FurnitureVM
...
@if (Model.MainImage != null)
{
    @Html.HiddenFor(m => m.MainImage.ID)
    @Html.HiddenFor(m => m.MainImage.Path)
    @Html.HiddenFor(m => m.MainImage.DisplayName)
    <img src="@Model.MainImage.Path" alt="@Model.MainImage.DisplayName" />
}

@Html.TextBoxFor(m => m.SecondaryFiles, new { type = "file", multiple = "multiple" })
@Html.ValidationMessageFor(m => m.SecondaryFiles)

@for (int i = 0; i < Model.SecondaryImages.Count; i++)
{
    @Html.HiddenFor(m => m.SecondaryImages[i].ID)
    @Html.HiddenFor(m => m.SecondaryImages[i].Path)
    @Html.HiddenFor(m => m.SecondaryImages[i].DisplayName)
    <img src="@Model.SecondaryImages[i].Path" alt="@Model.MainImage.DisplayName" />
}
23
  • can you show how the path looks like in the database that is stored, is it relative path? Commented Feb 14, 2017 at 6:32
  • @Ehsan Sajjad D:\visualstudio2015\FurnitureStore\FurnitureStore\Upload\4b44e4ce-59fc-4ba5-8f1d-719e1e8b1006..jpg how my path looks like Commented Feb 14, 2017 at 7:37
  • Note the Path.GetExtension(displayName); returns the .jpg (includes the dot) so it should be just string fileName = string.Format("{0}{1}", Guid.NewGuid(), extension); Commented Feb 14, 2017 at 9:51
  • @StephenMuecke okay I fix what you said , and image still doesn't displays imgh.us/1_3143.png Console in browser is clear , maybe I miss some parameters in my method in code above? Commented Feb 14, 2017 at 11:49
  • You have not shown any code in the GET method where you populate the MainImage or SecondayImages properties of FurnitureVM (so they are null and there is nothing to display (and not related, but add a property IEnumerable<SelectListItem> CategoryList and populate that and get rid of your ViewBag.CategoryId = ... code) Commented Feb 14, 2017 at 11:56

2 Answers 2

0

You should not be storing absolute path in the database, but instead store the relative path for which you would need to update the following line of code:

string path = "~/Upload/"+ fileName;
model.MainFile.SaveAs(Server.MapPath(path));

now in your view you would be able to display it this way:

<img src="@Url.Content(Model.MainImage.Path)" alt="@Model.MainImage.DisplayName" />

If you cannot modify the path saving logic and want to store the absolute path for any reason, then you can look at the following post:

https://stackoverflow.com/a/12804451/1875256

Sign up to request clarification or add additional context in comments.

1 Comment

hello , thanks I accept it as asnwer , but can u help me please , now I can't display Secondary Images , that's how I pass to model and my view pastebin.com/DpBsRB0a
0

Controller side Looks Fine You need to change View Code

and then the rest of things shall work Like

<img src="@Url.Content(Model.MainImage.Path)" alt="@Model.MainImage.DisplayName" />

OR

<img src="@Url.Content(Model.SecondaryImages[i].Path)" alt="@Model.MainImage.DisplayName" />

1 Comment

okay i tried your code , now I have an exception , value cannot be null , name: contentPath . This error in 1 line above from your code , here @Html.HiddenFor(m => m.MainImage.DisplayName)

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.