我正在创建一个Animal Shelter应用程序,当有人看动物时,我会使用自举卡显示它。我不知道如何显示图像。我对MVC和C#很新,所以我不理解这个特定问题在线发布的很多答案。
型号:
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);
}
查看:
<div class="container">
@foreach (var item in Model)
{
<div class="card col-md-3">
<img class="center-block" src="@Html.DisplayFor(modelItem => item.Photo)" height="300" width="230" alt=@Html.DisplayFor(modelItem => item.Name) />
// other display tags
</div>
}
Create() - 这就是我从上传中获取图片的方式
[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();
}
我试过这个方法,但它干扰了我的Create(),因为它无法将字符串转换为字节(我将我的模型从字符串Photo更改为byte [] Photo以尝试这种特殊方式)。
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) />