我是 ASP.NET MVC 的新手,请原谅我的错误。
我需要一个视图页面 ( index.cshtml
),我可以在其中显示图像,通过将图像存储在Varbinary(max)
SQL Server 表的列中来更改/删除图像。
数据库表中有这些列:
ID int primary key Identity not null,
ImageName nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null
我正在使用Image.cs
以下代码:
public class Image
{
public int ID {get; set;}
public string ImageName {get; set;}
public byte[] ImagePicInBytes {get; set;}
}
ImageContext
类如下
public class ImageContext : DbContext
{
public DbSet<Image> Images { get; set; }
}
连接字符串如下
<connectionStrings>
<add name="ImageContext"
connectionString="server=.; database=Sample; integrated security =SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
ImageController
如下
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
}
已创建如下视图
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// GET: /Image/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// POST: /Image/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Image image = db.Images.Find(id);
db.Images.Remove(image);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
我的 create.cshtml (视图)如下
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ImageName)
</th>
<th>
@Html.DisplayNameFor(model => model.ImagePicInBytes)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImageName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ImagePicInBytes)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
我有以下 3 个问题
如何通过将新图像从文件系统上传到
Varbinary
数据库中的列来在数据表中创建新记录?如何让视图在“创建视图”和“编辑视图”中有 FILEUPLOAD 控件
我可以
HttpPostedFileBase
用来实现上述目标Create.cshtml
吗?如果是:如何?有没有可用的建议或参考链接?