微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用ASP.NET MVC在“编辑产品”上加载图像?

如何解决如何使用ASP.NET MVC在“编辑产品”上加载图像?

我有一个用于ASP.NET MVC中产品的库存CRUD模块。在数据库中插入新产品时,我必须为每个产品加载图像。

这就是我所拥有的并且效果很好:

enter image description here

我的问题是,当我想在给定的ID中编辑现有产品时,以及在编辑产品时,文本加载成功,而图像加载失败。问题是我不知道该怎么办。

enter image description here

这是我的代码

插入新产品:

@using (Html.BeginForm("NuevoProducto","Inventario",FormMethod.Post,new { enctype = 
"multipart/form-data" }))
{
    ...
    <div class="form-group">
     <label for="exampleInputFile">Imagen</label>
      <div class="input-group">
       <div class="custom-file">
       <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>
        </div>
         @Html.ValidationMessageFor(m => m.Image,"",new { @class = "text-danger" })

          <div class="col-2">
     <p>Tamaño de Imagen</p>
     </div>
    </div>

}


[HttpPost]
    public ActionResult NuevoProducto(Productoviewmodel viewmodel)
    {

        string path = "";
        HttpPostedFileBase archivo = Request.Files["Image"];

        if (ModelState.IsValid)
        {

            if (archivo != null && archivo.ContentLength > 0)
            {
                path = Path.Combine(Server.MapPath("~/Images"),Path.GetFileName(archivo.FileName));
                archivo.SaveAs(path);

            }

            if (ModelState.IsValid) 
            { 
            var producto = viewmodel.Producto;
            producto.FechaCreacion = DateTime.Now;
            producto.Estado = true;
            producto.Imagen = viewmodel.Image.FileName;
            _productosRepository.Add(producto);
            TempData["Message"] = "¡El Producto se ha INSERTADO con éxito!";
            return RedirectToAction("Productos");
            }
        }

        viewmodel.Iniciar(_productosRepository);
        return View(viewmodel);

    }

public class Productoviewmodel
{

    public Producto Producto { get; set; } = new Producto();

    [required(ErrorMessage = "*Se necesita una imagen.")]
    public HttpPostedFileBase Image { get; set; }

}

这是我用于编辑产品的代码,但是图像无法加载:

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",new {viewmodel.Id});

        }

        viewmodel.Iniciar(_productosRepository);


        return View(viewmodel);
    }

我将图像文件夹中存储的图像的路径保存到数据库中,并使用 <img src="~/Images/@producto.Imagen" height="100" />。我不知道如何在编辑视图中加载Image并使之易于使用,因为保存在编辑视图中的图像为空。

解决方法

单击编辑按钮后,将图像名称和路径存储在tempdata中,并在更新过程中将其从tempdata中取回。

,

在编辑表单上添加preview 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>

以及在您的JavaScript代码中,如果您想通过选择按钮来显示所选图像:

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
 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。