【问题标题】:Can't display image from database using View Model无法使用视图模型显示数据库中的图像
【发布时间】:2017-02-14 06:21:21
【问题描述】:

我想在我的网站上为画廊和主页上传图像,所以我将图像上传到文件系统并将信息abvout图像保存在数据库中,我在数据库中使用一对多关系,也使用视图模型。数据库中的所有数据更新都没有问题,我检查了它,但是我无法在 View 中显示图像,也许我必须在我的方法 Edit 中写一些别的东西?请解释一下。所以这是我的代码: 查看模型

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

我在控制器中的方法:

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

我的部分观点

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

【问题讨论】:

  • 你能显示路径在存储的数据库中的样子吗?是相对路径吗?
  • @Ehsan Sajjad D:\visualstudio2015\FurnitureStore\FurnitureStore\Upload\4b44e4ce-59fc-4ba5-8f1d-719e1e8b1006..jpg 我的路径是什么样的
  • 注意Path.GetExtension(displayName); 返回.jpg(包括点)所以它应该只是string fileName = string.Format("{0}{1}", Guid.NewGuid(), extension);
  • @StephenMuecke 好的,我修复了你所说的,图像仍然不显示imgh.us/1_3143.png浏览器中的控制台很清晰,也许我在上面的代码中错过了我的方法中的一些参数?
  • 您没有在 GET 方法中显示任何代码,您在其中填充了 FurnitureVMMainImageSecondayImages 属性(因此它们是 null 并且没有任何内容可显示(而不是相关,但添加一个属性 IEnumerable&lt;SelectListItem&gt; CategoryList 并填充它并删除您的 ViewBag.CategoryId = ... 代码)

标签: asp.net asp.net-mvc database


【解决方案1】:

您不应该在数据库中存储绝对路径,而是存储您需要更新以下代码行的相对路径:

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

现在在您看来,您将能够以这种方式显示它:

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

如果不能修改路径保存逻辑,又想保存绝对路径,可以看下面的帖子:

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

【讨论】:

  • 你好,谢谢,我接受它作为 asnwer,但你能帮我吗,现在我无法显示次要图像,这就是我传递给模型和视图的方式pastebin.com/DpBsRB0a
【解决方案2】:

控制器端看起来不错你需要更改查看代码

然后剩下的事情就会像这样工作

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

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

【讨论】:

  • 好的,我试过你的代码,现在我有一个异常,值不能为空,名称:contentPath。上面 1 行代码中的此错误,此处为 @Html.HiddenFor(m => m.MainImage.DisplayName)
猜你喜欢
  • 1970-01-01
  • 2017-06-17
  • 2013-05-15
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多