我必须创建一个包含客户详细信息的ASP.NET MVC 4页面。 我必须创建一个表单,我必须执行客户创建,更新和删除。 不同的领域是...... 1)客户ID 2)客户名称 3)客户形象 4)客户地址 现在,我对Customer Image感到困惑。如何在数据库中存储Image以及如何在数据库中的Gridview中显示它。请解决我的问题,因为它对我来说非常重要..
答案 0 :(得分:1)
正如@LajosArpad所说,将图像保存为文件,只保存图像在数据库中的路径。
以下是创建客户的视图
<div class="box box-primary">
@using (Html.BeginForm("Create", "Customer", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal box-body">
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Image</label>
<div class="col-md-10">
<input class="form-control" name="image" type="file" />
</div>
</div>
</div>
<div class="box-footer">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
}
</div>
和控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "Id")] Customer customer, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var filePath = GetFilePath(image.FileName);
image.SaveAs(filePath);
customer.ImageUrl = "~/images/upload/" + Path.GetFileName(filePath);
}
// Save customer to database
return RedirectToAction("Index");
}
return View(news);
}
// Get absolute path for saving image and check it does not exist
public static string GetFilePath(string fileName)
{
var targetFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/images/upload/");
var targetPath = Path.Combine(targetFolder, fileName);
if (File.Exists(targetPath))
{
var name = Path.GetFileNameWithoutExtension(fileName);
name = name + "-" + (new Random()).Next();
var extension = Path.GetExtension(fileName);
name = name + extension;
GetFilePath(name);
}
return targetPath;
}
答案 1 :(得分:0)
将图像存储为文件,并将图像的路径存储在数据库中。如果我是你,我会生成文件名,而不是使用原始文件名,以确保它们不重复。因此,您无需将图像存储在数据库中,您可以将它们存储为单独的文件。