Listing the return of a Viewbag for View?

Asked

Viewed 566 times

1

Following the instructions of this post (Return the data to the View using Json.net or javascript-Asp.net mvc) answered by Loudenvier

was like this:

Class:

public class TB_RECEBE_IMAGENS
{
    public int Id { get; set; }
    public string Url { get; set; }
    public string Name { get; set; }
    public long Size { get; set; }
}

Controller:( here I need to bring the records , path of the images that is in the database, the doubt is here, the data of the "list")

//.......................................................

    public ActionResult VisualizaImagens()
    {
        var tbuscar = new CadastroImagemAplicacao();
        var listar = tbuscar.ListarTodos();

        //preencer os dados a baixo com o que vem do banco, 

        var model = new HomeViewModel
        {
            PreviewImages = new List<TB_RECEBE_IMAGENS> {
        new TB_RECEBE_IMAGENS { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg") },
        new TB_RECEBE_IMAGENS { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg") },
        new TB_RECEBE_IMAGENS { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg") },
        new TB_RECEBE_IMAGENS { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg") },
         },
            // size será preenchido depois (mas se vier do banco de dados, PREENCHA aqui para evitar perda de performance
            InitialPreviewConfigImages = new List<TB_RECEBE_IMAGENS> {
        new TB_RECEBE_IMAGENS { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg"), Name = "Food-1.jpg" },
        new TB_RECEBE_IMAGENS { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg"), Name = "Food-2.jpg" },
        new TB_RECEBE_IMAGENS { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg"), Name = "Food-3.jpg" },
        new TB_RECEBE_IMAGENS { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg"), Name = "Food-4.jpg" },
        }

        };
        FindFileSizes(model.InitialPreviewConfigImages);
        return View(model);
    }

    private void FindFileSizes(List<TB_RECEBE_IMAGENS> imgs)
    {
        foreach (var img in imgs)
        {
            // é preciso converter o caminho relativo da URL em um caminho físico no servidor
            var serverPath = Server.MapPath(img.Url);
            if (System.IO.File.Exists(serverPath))
            {
                img.Size = new System.IO.FileInfo(serverPath).Length;
            }
        }
    }

    //.......................................................

In View it was like this:

@model Projeto.FileInput.Models.HomeViewModel


@{
    ViewBag.Title = "VisualizaImagens";
}




<div class="container">
    <form enctype="multipart/form-data">
        <h1>Sending only 1 image</h1>
        <input id="Image1" type="file" name="imagens01[]" class="file" data-overwrite-initial="false" data-min-file-count="1">
    </form>
</div>



<script>

    $("#Image1").fileinput({
        uploadUrl: "@Url.Action("upload", "Home")",
        uploadAsync: false,
        minFileCount: 2,
        maxFileCount: 5,
        overwriteInitial: false,
        initialPreview: [
            @* Aqui using string.Join para montar os itens do array, tem um milhão de formas de fazer isso! *@
            @Html.Raw(string.Join(",\r\n        ",
            Model.PreviewImages.Select(img => "\"<img style='height:160px' src='" + img.Url + "'>\"")))
        ],
        initialPreviewConfig: [
        @* poderia ser feito com string.Join, mas resolvi mostrar outra forma com foreach e < text > *@
        @foreach (var img in Model.InitialPreviewConfigImages) {
            <text>{ caption: "@img.Name", size: @img.Size, width: "120px", url: "@Url.Action("remover", "Home")", key: @img.Id },</text>
        }
    ],
    uploadExtraData: {
                img_key: "1000",
        img_keywords: "happy, nature",
    }
        });
</script>

inserir a descrição da imagem aqui

  • I answered without using ViewBag. I used the model to make it easier to work, but it is quite simple to modify to use ViewBag.

  • Perhaps it is more interesting to create another question by checking how to list the image data as you want, otherwise the answer here can get too long! Put there the access code to the bank, the tables, etc. So we can respond within a more well defined scope. Put at least the code of CadastroDeImagens.ListarTodos, here in this question (if you prefer to keep everything in one place), or in the other.

  • http://answall.com/questions/161184/retorno-para-view-de-duas-tabelas-usando-homeviewmodel I asked a new question, thank you

1 answer

1

To fill the InitialPreviewConfig the same idea of what was done with the initialPreview. We add the fields Size and Name to send in the new field (we do not need to add values for this data in the initialPreview because the screen/page (view) does not use this data. We could even, to be purists, create two models for each type, but I find it totally unnecessary (for now).

One difficulty that will occur is calculating the file size, because it will require converting the relative path of an image to a physical path on the server to then get the file size using a . NET for file manipulation. This can be avoided if the file size is already registered in the database.

I kept the nomenclature previously used because the nomenclature used in the question completely escapes from the orientation for class names and methods in C#.

The modified code is as follows:

Controller

public ActionResult Index() {
    var model  = new HomeViewModel { 
        PreviewImages = new List<Imagem> {
            new Imagem { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg") },
            new Imagem { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg") },
            new Imagem { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg") },                
            new Imagem { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg") },
        },
        // size será preenchido depois (mas se vier do banco de dados, PREENCHA aqui para evitar perda de performance
        InitialPreviewConfigImages = new List<Imagem> {
            new Imagem { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg"), Name = "Food-1.jpg" },
            new Imagem { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg"), Name = "Food-2.jpg" },
            new Imagem { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg"), Name = "Food-3.jpg" },
            new Imagem { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg"), Name = "Food-4.jpg" },
        }
    };
    FindFileSizes(model.InitialPreviewConfigImages);
    return View(model);
}

private void FindFileSizes(List<Imagem> imgs) {
    foreach (var img in imgs) {
        // é preciso converter o caminho relativo da URL em um caminho físico no servidor
        var serverPath = Server.MapPath(img.Url);
        if (System.IO.File.Exists(serverPath)) {
            img.Size = new System.IO.FileInfo(serverPath).Length;
        }
    }
}

Remember that the data coming from a database should be dynamically loaded from there (if you have the size of the files already stored, you do not need to call FindFileSizes).

Viewmodel

public class HomeViewModel
{
    public HomeViewModel() {
        // apenas para garantir que NUNCA seja nulo! Facilica código na view
        PreviewImages = new List<Imagem>();
        InitialPreviewConfigImages = new List<Imagem>();
    }
    public List<Imagem> PreviewImages { get; set; }
    public List<Imagem> InitialPreviewConfigImages { get; set; }
}

Image class

public class Imagem
{
    public int Id { get; set; }
    public string Url { get; set; }
    public string Name { get; set; }
    public long Size { get; set; }
}

View code

@model SO_InitialPreviewMVC.Models.HomeViewModel
@{
    ViewBag.Title = "Home Page";
}

<script>

    $("#Image1").fileinput({
        uploadUrl: "@Url.Action("upload", "Home")",
        uploadAsync: false,
        minFileCount: 2,
        maxFileCount: 5,
        overwriteInitial: false,
        initialPreview: [
            @* Aqui using string.Join para montar os itens do array, tem um milhão de formas de fazer isso! *@
            @Html.Raw(string.Join(",\r\n        ",
            Model.PreviewImages.Select(img => "\"<img style='height:160px' src='" + img.Url + "'>\"")))
        ],
        initialPreviewConfig: [
        @* poderia ser feito com string.Join, mas resolvi mostrar outra forma com foreach e < text > *@
        @foreach (var img in Model.InitialPreviewConfigImages) {
            <text>{ caption: "@img.Name", size: @img.Size, width: "120px", url: "@Url.Action("remover", "Home")", key: @img.Id },</text>
        }
    ],
    uploadExtraData: {
                img_key: "1000",
        img_keywords: "happy, nature",
    }
        });
</script>

Upshot

<script>

    $("#Image1").fileinput({
        uploadUrl: "/Home/upload",
        uploadAsync: false,
        minFileCount: 2,
        maxFileCount: 5,
        overwriteInitial: false,
        initialPreview: [

            "<img style='height:160px' src='/Content/img/galeriaimagens/sl1.jpg'>",
        "<img style='height:160px' src='/Content/img/galeriaimagens/sl2.jpg'>",
        "<img style='height:160px' src='/Content/img/galeriaimagens/sl3.jpg'>",
        "<img style='height:160px' src='/Content/img/galeriaimagens/sl4.jpg'>"
        ],
        initialPreviewConfig: [
            { caption: "Food-1.jpg", size: 0, width: "120px", url: "/Home/remover", key: 1 },
            { caption: "Food-2.jpg", size: 0, width: "120px", url: "/Home/remover", key: 2 },
            { caption: "Food-3.jpg", size: 0, width: "120px", url: "/Home/remover", key: 3 },
            { caption: "Food-4.jpg", size: 0, width: "120px", url: "/Home/remover", key: 4 },
    ],
    uploadExtraData: {
                img_key: "1000",
        img_keywords: "happy, nature",
    }
        });
</script>
  • Loudenvier, one more fantastic answer, I don’t have words to thank you for your help, if you charged me I would even pay for the answer because you’re helping me too much, everything worked out, as you describe in the example, I’m just having a hard time getting the database data to fill out this Images table, since it’s the same fields. adjust the doubt with the final result and return of the "list" database that has the same fields that need to add

  • @itasouza this answer solved your problem? I did not know the result because you did not accept the answer! Is there anything that can help yet? If not, mark the answer so they know it helped you!

Browser other questions tagged

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