What’s the best way to get information to View?

Asked

Viewed 513 times

3

I have the following code:

   public ActionResult AtualizaCliente(int id)
    {
        ViewBag.idFoto = new SelectList(dao.fotos, "idFoto", "Foto");
        ViewBag.idInformacao = new  SelectList(dao.informacoes, "idInformacao", "titulo");
        return View(dao.cliente.Find(id));
    }


    private string PegarCaminhoImagem(Int16 controle)
    {
        sistema_mobileEntities dao = new sistema_mobileEntities();
        dao.fotos.Find(controle);
        var caminho = dao.fotos.First().Foto;
        return caminho;
    }


    public WebImage ObterWebImage(short idFoto)
    {
        int largura = 100;
        int altura = 100;
        String caminhoFoto = PegarCaminhoImagem(idFoto);
        return new WebImage(@caminhoFoto).Resize(largura, altura, false, false);
    }


    public ActionResult AtualizaFoto(Int16 caminhofoto)
    {
        try
        {
            WebImage webImagem = ObterWebImage(caminhofoto);
            return File(webImagem.GetBytes(), "image/png");
        }
        catch (Exception ex)
        {
            return Json("A Imagem não existe : " + ex.Message);
        }

    }


    public string ObterFotoBase64(Int16 caminhofoto)
    {
        try
        {
            WebImage webImagem = ObterWebImage(caminhofoto);
            return Convert.ToBase64String(webImagem.GetBytes());
        }
        catch (Exception ex)
        {
            return "A Imagem não existe : " + ex.Message;
        }
    }

in the Controller.

How best to pass the image path to be viewed?

@model ProjetoDelphiMobile.Models.cliente

@{
    ViewBag.Title = ""; 
}

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<script>
    $(document).ready(function () {
        $("#idFoto").on("change", function () {
            var srcRecebe = $($(this)).val();

            if (srcRecebe > 0) {
                $.post("@Url.Action("ObterFotoBase64", "ConsultaCliente")", { idFoto: srcRecebe }).done(function (data) {
                alert(data);
                $('#foto').attr("src", "data:image/image/png;base64," + data);
            });
        }
    });
});
</script>



<form>
    <fieldset data-role="controlgroup">


           <label>Foto:</label>
           <div id="selecao">
                 @Html.DropDownList("idFoto", String.Empty) 
           </div>
           <br />

          <div>
             <img id="foto" src="@Url.Action( "AtualizaFoto", "ConsultaCliente", new {caminhofoto = 1 })" alt="thumbnail" />
          </div>


           <br />

           <label>Nome:</label>
            @Html.TextBoxFor(model => model.nome, new { disabled = false })

           <label>Nome:</label>
            @Html.TextBoxFor(model => model.nome, new { disabled = false })

            <label>Nome do pai:</label>
            @Html.TextBoxFor(model => model.pai, new { disabled = false })

            <label>Nome da Mãe:</label>
            @Html.TextBoxFor(model => model.mae, new { disabled = false })

            <label>Data de Nascimento:</label>
            @Html.TextBoxFor(model => model.datanascimento, new { disabled = false })



        <ul data-role="listview" data-inset="true" data-divider-theme="e">
            <li><a href="/ConsultaCliente">Retornar para consulta</a></li>
        </ul>

    </fieldset>
</form>

1 answer

2

One solution for your case, which needs to load the image with both Ajax and Postback, is to use two different methods: one that returns the bytes of the image the way you were already doing and the other to return the serialized image in Base64. Then it would look more or less like this code (I adapted it to be able to test):

public WebImage ObterWebImage(short idFoto)
{
    int largura = 100;
    int altura = 100;
    String caminhoFoto = PegarCaminhoImagem(idFoto);
    return new WebImage(@caminhoFoto).Resize(largura, altura, false, false);
}

public ActionResult AtualizaFoto(Int16 caminhofoto)
{
    try
    {
        WebImage webImagem = ObterWebImage(caminhofoto);
        return File(webImagem.GetBytes(), "image/png");
    }
    catch (Exception ex)
    {
        return Json("A Imagem não existe : " + ex.Message);
    }

}

public string ObterFotoBase64(Int16 caminhofoto)
{
    try
    {
        WebImage webImagem = ObterWebImage(caminhofoto);
        return Convert.ToBase64String(webImagem.GetBytes());
    }
    catch (Exception ex)
    {
        return "A Imagem não existe : " + ex.Message;
    }
}

O Javascript:

$(document).ready(function () {
    $("#idFoto").on("change", function () {
        var srcRecebe = $($(this)).val();

        if (srcRecebe > 0) {
            $.post("@Url.Action("ObterFotoBase64", "ConsultaCliente")", { idFoto: srcRecebe }).done(function (data) {
                alert(data);
                $('#foto').attr("src", "data:image/image/png;base64," + data);
            });
        }
    });
});

And the Html:

<div>
    <img id="foto" src="@Url.Action( "AtualizaFoto", "Home", new {caminhofoto = 1 })" alt="thumbnail" />
</div>

Observing: I noticed that your code had some errors:

  • The second parameter of the method File of the Controller receives the content-type of the picture, you were passing the way;

  • As a result of $.post, you were trying to define the attribute src of an image with id "#way". By your code, the image id is "#photo";

  • The name of your parameter is "footpath" of type Int16. Wouldn’t it be more coherent to call this parameter "idFoto"? Because it can confuse, especially when calling the method from Javascript. In your code, in the view HTML, you are passing the parameter { caminhofoto = "caminho" } which gives error as it tries to convert the string "path" to Int16.

  • Apparently it worked, at the top of the page called the Updatephoto, but when selecting the Dropdownlist is not calling the Obtenfotobase64, I changed all the code to look like the one you passed, can help me?

  • The event change dropdown is being fired? If so, I found a difference in the controller name in my code. I tested using a controller named HomeController, but your controller calls ConsultaClienteController. Then the line of $.post should be $.post("@Url.Action("ObterFotoBase64", "ConsultaCliente")". Make sure your code is not being used HomeController as I was before in my reply.

  • In my question, I changed all the code according to the adjustment I made, $.post("@Url.Action("Get Photobase64", "Customer Consultation")",

  • Is the dropdown change event being triggered? The method ObterFotoBase64 controller is being called? Is it returning? jQuery crashed into the event done? Please, you need to specify what is going wrong, do a debug and tell us.

  • The Get photobase64 method is not being called! thanks!

Browser other questions tagged

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