Show Image in View

Asked

Viewed 535 times

0

I’m trying to adapt an example I’ve been taking here, to be saving the image in the folder, and show both in INDEX and EDIT, but there are some divergences. As follows below my source code, in case they may be guiding me in the sense that I can adjust the program so that it can work, I thank everyone who post in the assistance, grateful.

DOMINION

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MvcApp.Dominio
{
    public class FrmCadFuncionario : IDisposable
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        [DisplayName("Código")]
        public int T_FrmCadFuncionarioId { get; set; }

        [Required(ErrorMessage = "Digite o Nome")]
        [StringLength(50, MinimumLength = 1)]
        [DisplayName("Nome")]
        public string T_FrmCadFuncionarioNome { get; set; }

        [DisplayName("Foto")]
        public string T_FrmCadFuncionarioFoto { get; set; }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}

CONTROLLER

namespace MvcApp.Controllers
{
    public class FrmCadFuncionarioController : Controller
    {
        private IConnection Connection;
        private FrmCadFuncionarioAplicacao CadFuncionarioAplicacao;
        public FrmCadFuncionarioController()
        {
            Connection = new Connection();
            CadFuncionarioAplicacao = new FrmCadFuncionarioAplicacao(Connection);
        }

        protected override void Dispose(bool disposing)
        {
            if (CadFuncionarioAplicacao != null) CadFuncionarioAplicacao.Dispose();
            if (Connection != null) Connection.Dispose();
            base.Dispose(disposing);
        }

------ INDEX da paginas -----
        public ActionResult Index(int? page, string filtro)
        {
            ViewBag.filtro = filtro ?? string.Empty;
            return View(CadFuncionarioAplicacao.Pagination(page ?? 1, 10, filtro));
        }

----- CREATE -----  Esta gravando na pasta a imagem com o ID e a extensão do arquivo
public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FrmCadFuncionario cadfuncionario, HttpPostedFileBase file)
        {
            CadFuncionarioAplicacao.Create(cadfuncionario);
            if (file != null)
            {
                String[] strName = file.FileName.Split('.');
                String strExt = strName[strName.Count() - 1];
                string pathSave = String.Format("{0}{1}.{2}", Server.MapPath("~/Imagens/Fotos_Func/"), cadfuncionario.T_FrmCadFuncionarioId, strExt);
                String pathBase = String.Format("/Imagens/Fotos_Func/{0}.{1}", cadfuncionario.T_FrmCadFuncionarioId, strExt);
                file.SaveAs(pathSave);
                cadfuncionario.T_FrmCadFuncionarioPathFoto = pathBase;
            }

            return RedirectToAction("Index");
        }


-----EDIT - Não esta conseguindo encontrar a pasta das imagens
public ActionResult Edit(int id)
        {
            return View(CadFuncionarioAplicacao.Find(id));
        }

        [HttpPost]
        public ActionResult Edit(int id, FrmCadFuncionario cadfuncionario, HttpPostedFileBase file)
        {

            if (ModelState.IsValid)
            {
                CadFuncionarioAplicacao.Edit(cadfuncionario);
                if (file != null)
                {
                    if (cadfuncionario.T_FrmCadFuncionarioFoto != null)
                    {
                        if (System.IO.File.Exists(Server.MapPath("~/" + cadfuncionario.T_FrmCadFuncionarioFoto)))
                        {
                            System.IO.File.Delete(Server.MapPath("~/" + cadfuncionario.T_FrmCadFuncionarioFoto));
                        }
                    }
                    String[] strName = file.FileName.Split('.');
                    String strExt = strName[strName.Count() - 1];
                    string pathSave = String.Format("{0}{1}.{2}", Server.MapPath("~/Imagens/Fotos_Func/"), cadfuncionario.T_FrmCadFuncionarioId, strExt);
                    String pathBase = String.Format("/Imagens/Fotos_Func/{0}.{1}", cadfuncionario.T_FrmCadFuncionarioId, strExt);
                    file.SaveAs(pathSave);
                    cadfuncionario.T_FrmCadFuncionarioFoto = pathBase;
                    CadFuncionarioAplicacao.Edit(cadfuncionario);
                }
                return RedirectToAction("Index");
            }
            return View(cadfuncionario);
        }


---- INDEX - Não esta encontrando a pasta das imagens gravadas
        public ActionResult Index(HttpPostedFileBase[] files)
        {

            try
            {
                foreach (HttpPostedFileBase file in files)
                {
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    file.SaveAs(Server.MapPath("~/Imagens/Fotos_Func/" + filename));
                    string filepathtosave = "Imagens/Fotos_Func/" + filename;
                }
                ViewBag.Message = "Ocorreu com sucesso.";
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
            }
            finally
            {

            }
            return View();

        }



 VIEW INDEX - Não esta mostrando as imagens na tela
<div class="row-fluid">
                <div class="span12">
                    <h3 class="heading">Consulta Funcionários</h3>
                    <table class="table table-bordered table-striped table_vam" id="dt_gal">
                        <thead>
                            <tr>
                                <th class="table_checkbox"><input type="checkbox" name="select_rows" class="select_rows" data-tableid="dt_gal" /></th>

                                <th>Código</th>
                                <th data-bsortable="true">Nome</th>
                                <th>Endereço</th>
                                <th>Numero</th>
                                <th>Bairro</th>
                                <th>Cidade</th>
                                <th>Imagem</th>
                                <th>Acoes</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var Items in Model)
                            {
                                <tr>
                                    <td><input type="checkbox" name="row_sel" class="row_sel" /></td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioId)</td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioNome)</td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioEndereco)</td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioNumero)</td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioBairro_Nome)</td>
                                    <td>@Html.DisplayFor(c => Items.T_FrmCadFuncionarioCidade_Nome)</td>
                                    <td>
                                        <p>
                                            @Html.LabelFor(c => Items.T_FrmCadFuncionarioFoto)<br />
                                            <img src="@Html.DisplayFor(c => Items.T_FrmCadFuncionarioFoto)" alt="Uploaded Image" />
                                            <br />
                                        </p>
                                    </td>

                                    <td>
                                        <a href="@Url.Action("Edit", new { id = Items.T_FrmCadFuncionarioId})" class="sepV_a" title="Editar"><i class="icon-pencil"></i></a>
                                        <a href="@Url.Action("Delete", new { id = Items.T_FrmCadFuncionarioId })" title="Deletar"><i class="icon-trash"></i></a>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>

                </div>



VIEW EDIT - Não esta mostrando a imagem na tela
 @using (Html.BeginForm("Edit", "FrmCadFuncionario", FormMethod.Post, new { enctype = "multipart/form-data" }))
                    {
                        <fieldset>
                            <legend>Edit Registro </legend>
                           <div class="tab-content">
                                    <div class="formSep">
                                        <div class="span12">
                                            <div class="vcard">
                                                <div data-fileupload="image" class="fileupload fileupload-new">
                                                    <div style="width: 220px; height: 220px;" class="fileupload-new thumbnail">
                                                        <img src="~/Imagens/Fotos_Func/FundoImage.png" alt="" />
                                                    </div>
                                                    <div style="width: 220px; height: 220px; line-height: 220px;"
                                                         class="fileupload-preview fileupload-exists thumbnail">
                                                    </div>
                                                    <br />

                                                    <div class="form-horizontal">
                                                        <div class="row-fluid">
                                                            <span>       </span>
                                                            <div class="span2">
                                                                @Html.LabelFor(model => model.T_FrmCadFuncionarioId)
                                                                @Html.TextBoxFor(model => model.T_FrmCadFuncionarioId, new { style = "width:120px;", @class = "form-control", @readonly = "readonly" })
                                                                @Html.ValidationMessageFor(model => model.T_FrmCadFuncionarioId)
                                                            </div>

                                                    if (model.T_FrmCadFuncionarioFoto != null)
                                                        {
                                                        <div class="row-fluid">
                                                            <div class="span4">
                                                                <img src="~/Imagens/Fotos_Func/" alt="" />
                                                                @Html.LabelFor(model => model.T_FrmCadFuncionarioFoto)
                                                                @Html.TextBoxFor(model => model.T_FrmCadFuncionarioFoto, new { style = "width: 250px" })
                                                            </div>
                                                        </div>
                                                        }
                                                        else
                                                        {
                                                        <div class="row-fluid">
                                                            <div class="span4">
                                                                <img src="~/img/FundoImage.png" alt="" />
                                                                @Html.LabelFor(model => model.T_FrmCadFuncionarioFoto)
                                                                @Html.TextBoxFor(model => model.T_FrmCadFuncionarioFoto, new { @class = "file-loading", @type = "file", @name = "file" })
                                                            </div>
                                                        </div>
                                                       }

                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
  • I have done the project, aiming to include the employee image(photo) in the registration form, and when opening the records presented in the INDEX, also show the image. Only that in the operation of INDEX and EDIT, it is not showing the photo, that is the problem that is occurring in my code, in case someone has gone through this problem and want to guide me, I thank everyone who post in the assistance, grateful.

1 answer

0


Good morning user34823, You may be using the.CONTENT URL for this:

Example:

<img src="@Url.Content("~/Imagens/Fotos_Func/" + Items.T_FrmCadFuncionarioFoto)" alt="@Items.T_FrmCadFuncionarioNome" />

Any questions just ask!

  • Ola Oziel, I did as I described. Not appearing the image yet, I am grateful for the tip.obrg. <img src="@Url.Content("~/Images/Fotos_func/" + Items.T_frmcadfunctionaryofot)" alt="@Items.T_frmcadfunctionaryoid" />, inserted into the INDEX to verify. Obs.: Is not missing something in the controller so do not sample the image?.

  • I have done the project, aiming to include the employee image(photo) in the registration form, and when opening the records presented in the INDEX, also show the image. Only that in the operation of INDEX and EDIT, it is not showing the photo, that is the problem that is occurring in my code, in case someone has gone through this problem and want to guide me, I thank everyone who post in the assistance, grateful.

  • Hello good afternoon @user34823, I use this same code here for displaying images. Make sure some value is coming in your attributes Items.T_FrmCadFuncionarioFoto. The only difference from what I have here to what I have informed you is that I changed my URL attribute to the one in which you presented the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.