Show an image in mvc

Asked

Viewed 877 times

0

Hi, I’d like a hand.

I have the following controller to register an image and some fields, and the image property is string:

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Cadastrar(NoticiaViewModel vm, HttpPostedFileBase file)
        {
            try
            {
                vm.ComboCategoriaId = new CategoriaRepositorio().BuscarTodos().Select(x => new SelectListItem { Text = x.NomeCategoria, Value = Convert.ToString(x.CategoriaId) });
                if (!ModelState.IsValid)
                {
                    return View(vm);
                }
                var mapper = Mapper.Map<NoticiaViewModel, Noticia>(vm);
                _repositorio.Salvar(mapper);
                if (file != null)
                {
                    String[] strName = file.FileName.Split('.');
                    String strExt = strName[strName.Count() - 1];
                    string pathSave = String.Format("{0}{1}.{2}", Server.MapPath("~/Imagem/noticias/"), mapper.NoticiaId, strExt);
                    String pathBase = String.Format("/Imagem/noticias/{0}.{1}", mapper.NoticiaId, strExt);
                    file.SaveAs(pathSave);
                    mapper.Imagem = pathSave;
                    _repositorio.Atualizar(mapper);
                }

                TempData["mensagem"] = "Noticia cadastrada com sucesso";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

So far so good, I record the path where my image is. The problem is to show her:

        public ActionResult Visualizar(int id)
        {
            try
            {
                Noticia noticia = _repositorio.BuscarPorId(id);
                if (noticia == null)
                {
                    return HttpNotFound();
                }
                var mapper = Mapper.Map<Noticia, NoticiaViewModel>(noticia);
                return View(mapper);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

I am using this to bring from the database the data of a certain news:

To View is like this:

<div class="panel-body">
        <div class="col-md-12">
            <div class="form-group">
                <small class="text-right">@Model.DataCadastro</small>
            </div>
            <div class="form-group">
                <h3 class="text-left">Categoria: <b>@Model.Categoria.NomeCategoria</b></h3>
            </div>
            <div class="form-group">
                <h2 class="text-center">Título: @Model.Titulo</h2>
            </div>

            <div class="form-group">
                @MvcHtmlString.Create(Model.Descricao)
            </div>
            <div class="">
                <img src="@Model.Imagem" />
            </div>
        </div>
    </div> 

But the image does not appear.

Can someone give me a hand?

  • Your image is saved in the database ? If yes, in what type of data ?

  • No, I’m saving only her path, the image is inside the folder Image/ news

  • Take this example: http://answall.com/questions/45358/display-imagens-din%C3%A2mica-using-Razor? answertab=active#tab-top

  • Checks the path that is placed in the tag <img>

  • the path of my image is right that is this <img src="c: users Documents visual studio 2015 Projects IESB IESB.Presentation Image news 3.jpg" > it just does not appear

  • the image path has to be relative and not absolute

Show 1 more comment

1 answer

1

Hello, in your code change the following section:

   mapper.Imagem = pathSave;

for:

   mapper.Imagem = pathBase;

What you are basically doing is saving the physical path of your image, not the url to display. You can always get the physical path of the image through the Mappaht method as you did in your code, so there are no problems in saving the Url.

  • The two codes look the same to me. What’s the difference?

  • In the original code the property Mapper Image , which is used to store the image url to be displayed on the page in the img tag, is being assigned with the value of pathSave which is converted in the physical path from Server.MapPath. In my change I assign the Image property the value of pathBase which receives the relative Url, not the physical path.

  • @So when recording at the base and starts to record the relative path "/Image/news/image.jpg and no more C: projectodele Image News image.jpg". You may notice that this is the cause of the problem in the comment made by Alysson himself: "the path of my image is certain that is this <img src="c: users.

  • Yes, but see that your example the code of "from" and "to" are equal.

  • What changes is the assignment, from (mapper. Image = pathSave;) to (mapper. Image = pathBase;) is this the line in short that there really is a change.

  • Ah, good. Wouldn’t it be better to just leave that line instead of the four?

  • Corrected, thank you.

Show 2 more comments

Browser other questions tagged

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