C# MVC从数据库中检索照片,并使用引导卡在视图中显示
我正在创建一个动物收容所应用程序,当有人看到动物时,我会用引导卡显示它。但我不知道如何让图像显示出来。我对MVC和C非常陌生,所以我不理解网上发布的关于这个问题的很多答案 型号:C# MVC从数据库中检索照片,并使用引导卡在视图中显示,c#,asp.net-mvc,image,C#,Asp.net Mvc,Image,我正在创建一个动物收容所应用程序,当有人看到动物时,我会用引导卡显示它。但我不知道如何让图像显示出来。我对MVC和C非常陌生,所以我不理解网上发布的关于这个问题的很多答案 型号: public class Pet { public int Pet_ID { get; set; } // Other properties public string Photo { get; set; } } 控制器: public ActionResult ShowCats()
public class Pet
{
public int Pet_ID { get; set; }
// Other properties
public string Photo { get; set; }
}
控制器:
public ActionResult ShowCats()
{
var cats = db.Pets.Where(c => c.Species_Type == Species_Type.Cat).ToList();
return View(cats);
}
视图:
我尝试了这个方法,但它干扰了我的Create(),因为它无法将字符串转换为字节(我将模型从string Photo更改为byte[]Photo,以尝试这种特殊的方法)
这是它的观点:
<img class="center-block" src="@Url.Action("GetImage", "Pet", new { id = item.Pet_ID })" height="300" width="230" alt=@Html.DisplayFor(modelItem => item.Name) />
item.Name)/>
将~/Uploads/
存储在表中时,不要将其存储在imagepath
中。只需存储唯一的文件名。然后用它来设置图像,你能给我举个例子吗?我刚刚找到了这个上传文件的代码源,所以我不确定我到底该如何更改它。检查这个。它是针对asp.net核心的。但生成唯一的文件名和位置也适用于非核心代码。
[HttpPost]
public ActionResult Create(Pet upload, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/Uploads"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "~/Uploads/" + newpath;
upload.Photo = imagepath;
db.Pets.Add(upload);
db.SaveChanges();
}
TempData["Success"] = "Upload successful";
return RedirectToAction("Index");
}
return View();
}
public ActionResult GetImage( int id )
{
var photo = (new ApplicationDbContext()).Pets.Find(id).Photo;
return File( imageData, "image/jpg" );
}
<img class="center-block" src="@Url.Action("GetImage", "Pet", new { id = item.Pet_ID })" height="300" width="230" alt=@Html.DisplayFor(modelItem => item.Name) />