Listing the return of a ViewBag to the View?

0

Following the instructions in this post ( Return the data to the View using Json.net or javascript- asp.net mvc ) replied by Loudenvier

looks 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 looks 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>

    
asked by anonymous 25.10.2016 / 03:39

1 answer

0

To fill InitialPreviewConfig you must use the same idea as done with initialPreview . We added the Size and Name fields to send in the new field (we do not need to add values for this data in initialPreview because the screen / page does not use this data. for each type, but I find it totally unnecessary (for now).

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

I have maintained the nomenclature used previously because the nomenclature used in the question completely eludes 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 data coming from a database should be loaded dynamically from there (if it has the size of the files already stored, nor will it 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>

Result

<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>
    
25.10.2016 / 05:07