Asp.net mvc 4 ASP.NET MVC 4中的CRUD操作
我必须制作一个ASP.NETMVC4页面,其中包含客户详细信息。 我必须创建一个表单,在其中我必须执行客户创建、更新和删除。 不同的领域是。。 1) 客户ID 2) 客户名称 3) 客户形象 4) 客户地址Asp.net mvc 4 ASP.NET MVC 4中的CRUD操作,asp.net-mvc-4,crud,Asp.net Mvc 4,Crud,我必须制作一个ASP.NETMVC4页面,其中包含客户详细信息。 我必须创建一个表单,在其中我必须执行客户创建、更新和删除。 不同的领域是。。 1) 客户ID 2) 客户名称 3) 客户形象 4) 客户地址 现在,我对客户形象感到困惑。如何在数据库中存储图像以及如何从数据库在Gridview中显示图像。请解决我的问题,因为这对我非常重要。您将图像存储为文件,并将图像路径存储在数据库中。如果我是你,我会生成文件名,而不是使用原始文件名来确保它们不重复。因此,您不需要将图像存储在数据库中,您可以将它
现在,我对客户形象感到困惑。如何在数据库中存储图像以及如何从数据库在Gridview中显示图像。请解决我的问题,因为这对我非常重要。您将图像存储为文件,并将图像路径存储在数据库中。如果我是你,我会生成文件名,而不是使用原始文件名来确保它们不重复。因此,您不需要将图像存储在数据库中,您可以将它们存储为单独的文件。正如@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;
}