C# 如何将图像加载到";编辑产品";使用ASP.NETMVC?
我有一个ASP.NET MVC中产品的库存积垢模块。在数据库中插入新产品时,我必须为每个产品加载一个图像 这就是我所拥有的,并且非常有效: 我的问题是,当我想在给定Id中编辑现有产品时,以及当编辑产品文本成功加载但图像未加载时。问题是我不知道怎么做 这是我的代码: 插入新产品: 我将存储在Images文件夹中的图像路径保存到数据库中,并使用C# 如何将图像加载到";编辑产品";使用ASP.NETMVC?,c#,html,asp.net-mvc,razor,C#,Html,Asp.net Mvc,Razor,我有一个ASP.NET MVC中产品的库存积垢模块。在数据库中插入新产品时,我必须为每个产品加载一个图像 这就是我所拥有的,并且非常有效: 我的问题是,当我想在给定Id中编辑现有产品时,以及当编辑产品文本成功加载但图像未加载时。问题是我不知道怎么做 这是我的代码: 插入新产品: 我将存储在Images文件夹中的图像路径保存到数据库中,并使用 。我不知道如何在编辑视图中加载图像,并使我的客户端更容易,因为在编辑视图中保存图像会变为空。单击编辑按钮后,将图像名称和路径存储在tempdata中,并
。我不知道如何在编辑视图中加载图像,并使我的客户端更容易,因为在编辑视图中保存图像会变为空。单击编辑按钮后,将图像名称和路径存储在tempdata中,并在更新过程中从tempdata中取回。在编辑表单上添加一个预览div
。示例如下:
<div class="custom-file">
<div class="preview-image-section">
<img src='@Model.Image' class="preview-image" />
</div>
<input type="file" id="file" name="Image" class="custom-file-input" multiple onchange="GetFileSize()" />
<label class="custom-file-label" for="exampleInputFile">Elija Imagen</label>
</div>
如果用户上载新图像并替换现有加载的图像,该怎么办?它会工作吗?我正在使用
HttpPostedFileBase
请共享显示所有数据的视图检查您的代码,在您的操作方法ModificialProducto(int?Id)中,当您初始化productoEditViewModel时,您只是分配回Product属性而不是Image属性。你能检查一下吗?我找到你了,但也许我正在寻找加载视图时我想要的输入文件
填充图像路径。我想我必须用JS来编写代码。我已经有了图像路径。我想我还不够具体。您正试图显示图像,但我想这不是我想要的,因为如果需要,用户需要在input type=file
中替换图像。我认为,如果我使用给定的加载图像路径填充输入文件
,可能会更好。(不是在图像绘制)根据您的指定,我认为图像应该在显示之前上传。
public ActionResult ModificarProducto(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var producto = _productosRepository.Get((int)id, incluideRelatedEntities: false);
if (producto == null)
{
return HttpNotFound();
}
//necesito capturar los datos y almacenarlos en viewmodel
var viewModel = new ProductoEditViewModel()
{
Producto = producto
};
viewModel.Iniciar(_productosRepository);
return View(viewModel);
}
[HttpPost]
public ActionResult ModificarProducto(ProductoEditViewModel viewModel)
{
if (ModelState.IsValid)
{
var producto = viewModel.Producto;
_productosRepository.ModificarProducto(producto);
TempData["Message"] = "¡El Producto se ha MODIFICADO con éxito!";
return RedirectToAction("DetallesProducto", "Inventario", new {viewModel.Id});
}
viewModel.Iniciar(_productosRepository);
return View(viewModel);
}
<div class="custom-file">
<div class="preview-image-section">
<img src='@Model.Image' class="preview-image" />
</div>
<input type="file" id="file" name="Image" class="custom-file-input" multiple onchange="GetFileSize()" />
<label class="custom-file-label" for="exampleInputFile">Elija Imagen</label>
</div>
function GetFileSize() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.addEventListener("load", function (e) {
$(".preview-image").attr('src', e.target.result);
});
FR.readAsDataURL(this.files[0]);
}
//your code here
}