Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 13
  1. #1

    [C# - 4.6] Passaggio di valori da View a Controller

    Ciao,
    nella speranza di trovare aiuto e darlo ai prossimi dopo di me, espongo il mio problema.

    Nel nostro programma c'è una sezione di ricerca, i cui risultati appaiono in una tabella.
    Gli elementi di questa tabella sono una serie di informazioni (Id, nome, cognome, etc...) presi da un database tramite MVC.

    Vorrei riuscire a scaricare queste informazioni in un foglio Excel.
    Nella pagina .cs ho già costruito una funzione che viene richiamata dalla view e che tramite la libreria NPOI costruisce il File Excel.
    La funzione però accede direttamente al DB, non tiene conto dei dati nella ricerca.
    Io invece vorrei tenerne conto per scaricare solo i risultati ricercati.

    Per fare ciò, sarebbe molto bello prendere semplicemente la variabile "ViewBag" e darla in pasto alla funzione, ma non ci riesco.
    In alternativa mi basterebbe riuscire ad avere almeno l'Id, così da poter costruire l'Excel con le informazioni nella riga dell'Id presente.

    Adesso posto il codice.

    codice:
    [...]
    <tbody class="table-custom-clickable-row">
    @foreach (var item in Model)
                            {
                                <tr class="clickable-row" data-href="@Url.Action("Details", new { id = item.Id, socId = item.SocietaId })">
                                    <td>
    @Html.DisplayFor(modelItem => item.Id)/
    @Html.DisplayFor(modelItem => item.SocietaId)
                                    </td>
                                    <td>@Html.DisplayFor(modelItem => item.userModifica.UserName)</td>
                                    <td>@Html.DisplayFor(modelItem => item.societaTrat.NomeSocieta)</td>
                                    <td>@Html.DisplayFor(modelItem => item.societaTrat.RuoloSocieta)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.Finalita)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.CategoriaDati)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.FunzioneAziendale)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.ApplicativiCorrelati)</td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.DataModifica)
                                    </td>
                                    <td class="text-center">
                                        @if (item.Stato == RegistroPrivacy.Models.Stato.NonConvalidato)
                                        {
                                            <i class="fa fa-2x fa-dot-circle-o" style="color:gold"></i>
                                        }
                                        else
                                        {
                                            <i class="fa fa-2x fa-dot-circle-o" style="color:green"></i>
                                        }
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
    [...]
    Questa è la parte di codice della view .cshtml, che mostra la tabella con le informazioni.
    Come potete vedere i valori vengono presi e sputati dinamicamente (parte in grassetto) dalla variabile item ("punto qualcosa").
    Ho provato a prendere la variabile item e darla in input alla funzione, ma non funziona...
    immagino che forse essendo dentro un ciclo "foreach", la variabile item muoia appena finisce il ciclo, giusto?

    In seguito creo un pulsante per richiamare la funzione "GetMessage()":

    codice:
    <div>
    <input class="btn btn-info-custom" type="button" onclick="GetMessage()" value="Scarica Excel"/>
    <p></p>
    Funzione presente in una sezione di script Javascript:

    codice:
    <script>
    function GetMessage() 
        {
            $.get("/RPImport/GetMessage", function (data) 
            {
                $("p").html(data);
            });
        }
    </script>
    
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    Nella pagina .cs invece ho la funzione vera e propria che funziona, creo il foglio Excel e riesco ad accedere al DB.
    Però mi servirebbe almeno l'Id e il SocietaId per andare a prendere i valori giusti.

    codice:
    public ActionResult GetMessage()
            {
                HSSFWorkbook hssfworkbook = new HSSFWorkbook();
    
    
                //Apertura istanza database
                using (var context = new Models.SocietaModelContainer("sdemo"))
                {
                    var Responsabile = context.RPSoggettiPartecipantiSet.Local[0].Id;
                }
    [Etc...]

    In un altro programma (costruito da me in modo più semplice) facevo una cosa tipo:
    codice:
    serverInput = Request["serverSelect"];
    Però potevo farlo perchè il valore era dentro un menù a tendina ed era presente il tag "id=serverSelect" dell'elemento html.
    Invece qui non so come fare.. ho provato ad assegnare un id al tag <td> della tabella, ma non funziona, anche perchè poi con la costruzione dinamica, ho più tag associati allo stesso id e questo è sicuramente un problema.

    Qualche suggerimento?

    Cordialmente,
    Raimondo


    Ps: nelle pagine seguenti posto il codice completo, ho fatto dei ritagli perchè così è più chiaro secondo me
    Ultima modifica di RayanHawkins; 03-05-2018 a 15:39

  2. #2
    Pagina .cshtml

    codice:
    @model PagedList.IPagedList<RegistroPrivacy.Models.RPTrattamento>
    @using PagedList.Mvc;
    @using SocietaModelProperties;
    
    
    @{
        ViewBag.Title = SocietaModelProperties.ricercaTratt;
    }
    
    
    <div class="panel">
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <h2 class="text-center">@ViewBag.Title</h2>
    
    
                    <hr />
    
    
                    <table>
                        <tr>
                            <td class="col-md-1"><button id="toggleFiltru" class="btn btn-info-custom col-lg-12">Filtro</button></td>
                            <td class="col-md-10"></td>
                            <td class="col-md-1"><a href="@Url.Action("Create")" class="btn btn-next-custom col-lg-12"> Nuovo@*@SocietaModelProperties.nuovoTratt*@ <span class="glyphicon glyphicon-plus-sign"></span> </a></td>
                        </tr>
                    </table>
    
    
                    @using (Html.BeginForm("Index", "RPTrattamento", FormMethod.Get, new { id = "cercaTratt" }))
                    {
                        <br />
                    
                        <table id="filtru" class="col-lg-12" style="display:none;">
                            <tr>
                                <td class="col-lg-3">
                                    <div class="btn-group">
                                        @Html.DropDownList("userId", new SelectList(ViewBag.usersSocieta, "Id", "UserName", ViewBag.searchedUser), "-Utente-", new { @class = "form-control align-middle col-lg-12", style = "padding-bottom:3px;" })
                                    </div>
                                </td>
                                <td class="col-lg-3">
                                    <div class="btn-group col-sm-12">
                                        @Html.DropDownList("societaId", new SelectList(ViewBag.allSoc, "Id", "NomeSocieta", ViewBag.searchedSocieta), "-Società-", new { @class = "form-control align-middle col-lg-12", style = "padding-bottom:3px;", id = "societaSelect" })
                                    </div>
                                </td>
                                <td class="col-lg-3">
                                    <div class="btn-group col-sm-12">
                                        @Html.DropDownList("ruolo", new SelectList(ViewBag.ruoliSocieta, ViewBag.searchedRuolo), "Ruolo Soc", new { @class = "form-control align-middle col-lg-12", style = "padding-bottom:3px;" })
                                    </div>
                                </td>
                                <td class="col-lg-3">
                                    <div class="btn-group col-sm-12">
                                        @Html.DropDownList("stato", new SelectList((List<string>)ViewBag.statoTratt, (string)ViewBag.searchedStato), "Stato", new { @class = "form-control align-middle col-lg-12", style = "padding-bottom:3px;" })
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="col-lg-2">
                                    <div class="input-group">
                                        @Html.TextBox("finalitaString", ViewBag.CurrentFilter as string, new { @class = "form-control", placeholder = "Finalita" })
                                    </div>
                                </td>
                                <td class="col-md-2">
                                    <div class="input-group col-lg-12">
                                        @Html.TextBox("categDati", ViewBag.categDati as string, new { @class = "form-control", placeholder = "Categoria Dati" })
                                    </div>
                                </td>
                                <td class="col-md-2">
                                    <div class="input-group col-lg-12">
                                        @Html.TextBox("funzioneString", ViewBag.funzioneString as string, new { @class = "form-control", placeholder = "Funzioni" })
                                    </div>
                                </td>
    
    
                                <td class="col-md-2">
                                    <div class="input-group col-lg-12">
                                        @Html.TextBox("applicativoString", ViewBag.applicativoString as string, new { @class = "form-control", placeholder = "Applicativo" })
                                    </div>
                                </td>
                                </tr>
                                <tr>
                                <td class="text-center"><button type="button" class="btn btn-danger-custom" onclick="location.href='@Url.Action("Index", "RPTrattamento")'">Reset</button></td>
                                <td class="col-md-2">
                                    <div class="input-group col-lg-12">
                                        @Html.TextBox("aggiornamentoDa", ViewBag.aggiornamentoDa as string, new { @class = "form-control", type = "date" })
                                    </div>
                                </td>
                                <td class="col-md-2 ">
                                    <div class="input-group col-lg-12">
                                        @Html.TextBox("aggiornamentoA", ViewBag.aggiornamentoA as string, new { @class = "form-control", type = "date" })
                                    </div>
                                </td>
                                
                                <td class="text-center"><button class="btn btn-info-custom">Cerca <span class="glyphicon glyphicon-search" onclick="document.getElementById('cercaTratt').submit();"></span></button></td>
                            </tr>
                        </table>
                    }
    
    
                    <br />
    
    
                    <table class="table table-striped table-custom">
                        <thead>
                            <tr>
                                <th>
                                    <a href="@Url.Action("Index", new { sortOrder = ViewBag.IdSortParam, currentFilter=ViewBag.CurrentFilter, societaId = ViewBag.searchedSocieta, userId = ViewBag.searchedUser, ruolo = ViewBag.searchedRuolo, categDati = ViewBag.categDati, funzioneString = ViewBag.funzioneString, applicativoString = ViewBag.applicativoString, aggiornamentoDa = ViewBag.aggiornamentoDa, aggiornamentoA = ViewBag.aggiornamentoA, stato = ViewBag.searchedStato})">
                                        @SocietaModelProperties.trattId/ @SocietaModelProperties.trattSocietaId  @if ("descresc".Equals(ViewBag.IdSort))
                                        {@Html.Raw("&darr;") }
                                    else if ("cresc".Equals(ViewBag.IdSort))
                                    { @Html.Raw("&uarr;")}
                                    </a>
                                </th>
                                <th>
                                    @SocietaModelProperties.trattUtenteMod 
                                </th>
                                <th>Società</th>
                                <th>Ruolo</th>
                                <th>Finalità</th>
                                <th>Categorie di dati</th>
                                <th>Funzione</th>
                                <th>Applicativo</th>
                                <th>
                                    <a href="@Url.Action("Index", new { sortOrder = ViewBag.DateSortParam, currentFilter=ViewBag.CurrentFilter, societaId = ViewBag.searchedSocieta, userId = ViewBag.searchedUser, ruolo = ViewBag.searchedRuolo, categDati = ViewBag.categDati, funzioneString = ViewBag.funzioneString, applicativoString = ViewBag.applicativoString, aggiornamentoDa = ViewBag.aggiornamentoDa, aggiornamentoA = ViewBag.aggiornamentoA, stato = ViewBag.searchedStato})">
                                        @SocietaModelProperties.trattDataMod @if ("descresc".Equals(ViewBag.DateSort))
                                        {@Html.Raw("&darr;") }
                                    else if ("cresc".Equals(ViewBag.DateSort))
                                    { @Html.Raw("&uarr;")}
                                    </a>
    
    
                                </th>
                                <th>
                                    <a href="@Url.Action("Index", new { sortOrder = ViewBag.StatoSortParam, currentFilter=ViewBag.CurrentFilter, societaId = ViewBag.searchedSocieta, userId = ViewBag.searchedUser, ruolo = ViewBag.searchedRuolo, categDati = ViewBag.categDati, funzioneString = ViewBag.funzioneString, applicativoString = ViewBag.applicativoString, aggiornamentoDa = ViewBag.aggiornamentoDa, aggiornamentoA = ViewBag.aggiornamentoA, stato = ViewBag.searchedStato})">
                                        @SocietaModelProperties.trattStato @if ("descresc".Equals(ViewBag.StatoSort))
                                        {@Html.Raw("&darr;") }
                                    else if ("cresc".Equals(ViewBag.StatoSort))
                                    { @Html.Raw("&uarr;")}
                                    </a>
                                </th>
                            </tr>
                        </thead>
                        <tbody class="table-custom-clickable-row">
                            @foreach (var item in Model)
                            {
                                <tr class="clickable-row" data-href="@Url.Action("Details", new { id = item.Id, socId = item.SocietaId })">
                                    <td>
                                        @Html.DisplayFor(modelItem => item.Id)/
    @Html.DisplayFor(modelItem => item.SocietaId)
                                    </td>
                                    <td>@Html.DisplayFor(modelItem => item.userModifica.UserName)</td>
                                    <td>@Html.DisplayFor(modelItem => item.societaTrat.NomeSocieta)</td>
                                    <td>@Html.DisplayFor(modelItem => item.societaTrat.RuoloSocieta)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.Finalita)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.CategoriaDati)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.FunzioneAziendale)</td>
                                    <td>@Html.DisplayFor(modelItem => item.InformazioniAttivita.ApplicativiCorrelati)</td>
                                    <td>
                                        @Html.DisplayFor(modelItem => item.DataModifica)
                                    </td>
                                    <td class="text-center">
                                        @if (item.Stato == RegistroPrivacy.Models.Stato.NonConvalidato)
                                        {
                                            <i class="fa fa-2x fa-dot-circle-o" style="color:gold"></i>
                                        }
                                        else
                                        {
                                            <i class="fa fa-2x fa-dot-circle-o" style="color:green"></i>
                                        }
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
    
    
                    <br />
    
    
                    <div class="col-md-12">
                        <div class="col-md-6 text-left">
                            Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
                            @Html.PagedListPager(Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter, societaId = ViewBag.searchedSocieta, userId = ViewBag.searchedUser, ruolo = ViewBag.searchedRuolo, categDati = ViewBag.categDati, funzioneString = ViewBag.funzioneString, applicativoString = ViewBag.applicativoString, aggiornamentoDa = ViewBag.aggiornamentoDa, aggiornamentoA = ViewBag.aggiornamentoA, stato = ViewBag.searchedStato }))
                        </div>
                        <div>
    <input class="btn btn-info-custom" type="button" onclick="GetMessage()" value="Scarica Excel"/>
    <p></p>
                        </div>
                        <div class="col-md-6 text-right">
                            <strong>Trattamenti trovati: @ViewBag.countResult</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    
    <script>
        jQuery(document).ready(function ($) {
            $(".clickable-row").click(function () {
                window.location = $(this).data("href");
            });
        });
    </script>
    
    
    <script>
        $(document).ready(function () {
            $("#toggleFiltru").click(function () {
                $("#filtru").toggle();
            });
        });
    </script>
    
    
    <script>
    function GetMessage() 
    {
    $.get("/RPImport/GetMessage", function (data) 
    {
    $("p").html(data);
    });
    }
    </script>
    
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    Ultima modifica di RayanHawkins; 03-05-2018 a 15:42

  3. #3
    Pagina .cs:

    codice:
    using ExcelDataReader;
    using RegistroPrivacy.Helpers;
    using RegistroPrivacy.Models;
    using System;
    using RegistroPrivacy.Repositories;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Web;
    using System.Web.Mvc;
    using NPOI.HPSF;
    using NPOI.HSSF.UserModel;
    using NPOI.POIFS.FileSystem;
    using NPOI.SS.UserModel;
    using System.Text;
    using NPOI.SS.Util;
    using System.Data.Entity.Core.EntityClient;
    
    
    namespace RegistroPrivacy.Controllers
    {
        [UFRPUserAuthorize(Roles = "Admin")]
        [UFRPUserPasswordCheckAttribute]
        public class RPImportController : Controller
        {
            static public byte[] b;
            string message = "";
    
    
            private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
    
            readonly ISocietaRepository societaRepository;
            readonly IRPImportHelper importHelper;
    
    
            public RPImportController(IRPImportHelper importHelper, ISocietaRepository societaRepository)
            {
                this.importHelper = importHelper;
                this.societaRepository = societaRepository;
            }
    
    
            // GET: RPImport
            public ActionResult ImportData()
            {
                return View();
            }
    
    
            // POST: RPImport
            [HttpPost]
            [ValidateAntiForgeryToken]
            [LogFilter]
            public ActionResult ImportData(HttpPostedFileBase uploadfile)
            {
                if (ModelState.IsValid)
                {
                    if (uploadfile != null && uploadfile.ContentLength > 0)
                    {
                        IExcelDataReader reader = null;
                        Stream stream = uploadfile.InputStream;
                        DataSet result = null;
    
    
                        try
                        {
                            reader = ExcelReaderFactory.CreateReader(stream);
                            result = reader.AsDataSet();
                        } catch (Exception e)
                        {
                            log.Fatal(e);
                            ModelState.AddModelError("uploadfile", SocietaModelMessages.SocietaModelMessages.invalidFormat);
                            return View();
                        } finally
                        {
                            if (reader!=null)
                            {
                                reader.Close();
                            }
                        }
    
    
                        DataTable dataTable = result.Tables[0];
    
    
                        var validationErrors = importHelper.validate(dataTable, User);
    
    
                        if (validationErrors.Count == 0)
                        {
                            List<RPTrattamento> tuttiTrattamenti = importHelper.tranformData(dataTable, User);
                            var trattamentiPerSocieta = new Dictionary<int, List<RPTrattamento>>();
    
    
                            foreach (var trattamento in tuttiTrattamenti)
                            {
                                if (!trattamentiPerSocieta.ContainsKey(trattamento.SocietaId))
                                {
                                    var listSocieta = new List<RPTrattamento>();
                                    listSocieta.Add(trattamento);
                                    trattamentiPerSocieta.Add(trattamento.SocietaId, listSocieta);
                                } else
                                {
                                    var listSocieta = trattamentiPerSocieta[trattamento.SocietaId];
                                    listSocieta.Add(trattamento);
                                }
                                
                            }
    
    
                            var message = new List<string>();
                            foreach (var item in trattamentiPerSocieta)
                            {
                                int societaId = item.Key;
                                var db = new SocietaModelContainer(societaRepository.GetSocietaContext(societaId));
                                db.RPTrattamentoSet.AddRange(item.Value);
                                db.SaveChanges();
                                message.Add(string.Format(SocietaModelMessages.SocietaModelMessages.importOk, item.Value.Count, uploadfile.FileName, societaRepository.GetSocieta(societaId).NomeSocieta));
                            }
                            TempData["succes"] = message;
    
    
                        } else
                        {
                            foreach (var validationItem in validationErrors)
                            {
                                ModelState.AddModelError(validationItem.Key, validationItem.Value);
                            }
                        }
    
    
    
    
                        return View();
                    }
                }
    
    
                return View();
            }
    
    
            public ActionResult GetMessage()
            {
                HSSFWorkbook hssfworkbook = new HSSFWorkbook();
    
                //Apertura istanza tabelle database
                using (var context = new Models.SocietaModelContainer("sdemo"))
                {
                    var Responsabile = context.RPSoggettiPartecipantiSet.Local[0].Id;
                }
    
    
                ////create a entry of DocumentSummaryInformation
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "NPOI Team";
                hssfworkbook.DocumentSummaryInformation = dsi;
    
    
                ////create a entry of SummaryInformation
                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Subject = "NPOI SDK Example";
                hssfworkbook.SummaryInformation = si;
    
    
                //here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
                //So we insert three sheet just like what Excel does
                ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
                IRow row0 = sheet1.CreateRow(0);
                IRow row1 = sheet1.CreateRow(1);
                IRow row2 = sheet1.CreateRow(2);
    
    
                IFont font1 = hssfworkbook.CreateFont();
                font1.FontHeightInPoints = 28;
                font1.Boldweight = (short)FontBoldWeight.Bold;
    
    
                IFont font2 = hssfworkbook.CreateFont();
                font2.FontHeightInPoints = 11;
                font2.Boldweight = (short)FontBoldWeight.Bold;
    
    
                IFont font3 = hssfworkbook.CreateFont();
                font3.FontHeightInPoints = 8;
                font3.Boldweight = (short)FontBoldWeight.Normal;
    
    
    
    
                ICellStyle styleCenter1 = hssfworkbook.CreateCellStyle();
                styleCenter1.Alignment = HorizontalAlignment.Center;
                styleCenter1.VerticalAlignment = VerticalAlignment.Center;
                styleCenter1.WrapText = true;
                styleCenter1.SetFont(font1);
                //styleCenter1.BorderBottom = BorderStyle.Thick;
                //styleCenter1.BorderLeft = BorderStyle.Thick;
                //styleCenter1.BorderRight = BorderStyle.Thick;
                //styleCenter1.BorderTop = BorderStyle.Thick;
    
    
                ICellStyle styleCenter2 = hssfworkbook.CreateCellStyle();
                styleCenter2.Alignment = HorizontalAlignment.Center;
                styleCenter2.VerticalAlignment = VerticalAlignment.Center;
                styleCenter2.WrapText = true;
                styleCenter2.SetFont(font2);
    
    
                ICellStyle styleCenter3 = hssfworkbook.CreateCellStyle();
                styleCenter3.Alignment = HorizontalAlignment.Center;
                styleCenter3.VerticalAlignment = VerticalAlignment.Center;
                styleCenter3.WrapText = true;
                styleCenter3.SetFont(font3);
                
    
    
                row0.CreateCell(0).SetCellValue("REGISTRO ATTIVITÀ DI TRATTAMENTO DEL TITOLARE");
                sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 23));
                row0.Height = 50 * 20;
                row0.GetCell(0).CellStyle = styleCenter1;
    
    
    
    
                row1.CreateCell(0).SetCellValue("Soggetti partecipanti al trattamento");
                sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 0, 4));
                row1.GetCell(0).CellStyle = styleCenter2;
    
    
                row1.CreateCell(5).SetCellValue("Informazioni sulle attività di trattamento");
                sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 5, 16));
                row1.GetCell(5).CellStyle = styleCenter2;
    
    
                row1.CreateCell(17).SetCellValue("Misure di sicurezza tecniche ed organizzative e rischi");
                sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 17, 19));
                row1.GetCell(17).CellStyle = styleCenter2;
    
    
                row1.CreateCell(20).SetCellValue("Trasferimento verso Paese terzo (se previsto)");
                sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 20, 22));
                row1.GetCell(20).CellStyle = styleCenter2;
    
    
                row1.CreateCell(23).SetCellValue("Note lavoro");
                row1.GetCell(23).CellStyle = styleCenter2;
    
    
                
                row2.CreateCell(0).SetCellValue("Nome Società Titolare del trattamento");
                row2.CreateCell(1).SetCellValue("Responsabile del trattamento (se previsto)");
                row2.CreateCell(2).SetCellValue("Responsabile della protezione dei dati (se nominato)");
                row2.CreateCell(3).SetCellValue("Rappresentante UE del Titolare non stabiliti nell'UE (se previsto)");
                row2.CreateCell(4).SetCellValue("Contatti Contitolare");
                row2.CreateCell(5).SetCellValue("Funzione Aziendale");
                row2.CreateCell(6).SetCellValue("Attività di trattamento");
                row2.CreateCell(7).SetCellValue("Descrizione dettagliata del trattamento");
                row2.CreateCell(8).SetCellValue("Finalità del trattamento");
                row2.CreateCell(9).SetCellValue("Interessati al trattamento dei dati");
                row2.CreateCell(10).SetCellValue("Categoria dati");
                row2.CreateCell(11).SetCellValue("Approfondimento categoria dati");
                row2.CreateCell(12).SetCellValue("Base giuridica del trattamento");
                row2.CreateCell(13).SetCellValue("Categoria destinatari a cui i dati personali sono stati o saranno comunicati / Società del gruppo a cui sono trasferiti i dati (se previsto)");
                row2.CreateCell(14).SetCellValue("Termine cancellazione dei dati o criteri adottati");
                row2.CreateCell(15).SetCellValue("Tipo di trattamento (automatizzato o non)");
                row2.CreateCell(16).SetCellValue("Applicativi correlati al trattamento");
                row2.CreateCell(17).SetCellValue("Descrizione delle misure di sicurezza organizzative e tecniche");
                row2.CreateCell(18).SetCellValue("Descrizione del rischio per l'interessato");
                row2.CreateCell(19).SetCellValue("Data breach - casi possibili");
                row2.CreateCell(20).SetCellValue("Paese o Organizzazione a cui si invia");
                row2.CreateCell(21).SetCellValue("Paese o Organizzazione da cui si riceve");
                row2.CreateCell(22).SetCellValue("Garanzie ex art. 49 GDPR");
                for (int i=0;i<23;i++)
                {
                    row2.GetCell(i).CellStyle = styleCenter3;
                }
                
    
    
                int x = 1;
                for (int i = 3; i <= 10; i++)
                {
                    IRow row = sheet1.CreateRow(i);
                    for (int j = 0; j < 24; j++)
                    {
                        row.CreateCell(j).SetCellValue(x++);
                        row.GetCell(j).CellStyle = styleCenter3;
                    }
                }
    
    
    
    
                //Write the stream data of workbook to the root directory
                FileStream file = new FileStream(@"C:\Users\buffo\Desktop\test.xls", FileMode.Create);
                hssfworkbook.Write(file);
                file.Close();
    
    
                //try
                //{
                //    MemoryStream bos = new MemoryStream();
                //    try
                //    {
                //        hssfworkbook.Write(bos);
                //    }
                //    finally
                //    {
                //        bos.Close();
                //    }
                //    b = bos.ToArray();
    
    
    
    
                //    Response.Clear();
                //    Response.AddHeader("content-disposition", "attachment;filename=test.xlsx");
                //    Response.Charset = "";
                //    Response.Cache.SetNoServerCaching();
                //    Response.ContentType = "application/ms-excel";
                //    Response.BinaryWrite(b);
                //}
                //catch (Exception)
                //{
                //    message = "Download non riuscito";
                //    return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                //}
                
                message = "Download eseguito";
                return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
    }

  4. #4
    Moderatore di ASP.net L'avatar di djciko
    Registrato dal
    Nov 2002
    Messaggi
    6,886
    e' molto lungo il post, ma usare la Session ?

    anche in MVC funziona...
    https://stackoverflow.com/questions/...-4-application

  5. #5
    Fatto, grazie mille per il suggerimento Djciko!
    Mi ero completamente dimenticato della session, che stupido


    Soluzione:

    Pagina view.cshtml
    codice:
    //Memorizza la variabile
    @{Session["viewbag"]= ViewBag;}
    Pagina controller.cs
    codice:
    //assegna la variabile memorizzata a una variabile locale
    var viewBag = Session["viewbag"];

  6. #6
    Ps: ho un problema...

    la variabile "viewbag" contiene gli elementi che mi servono, però sono "Membri non pubblici" e quindi posso accedervi solo in debug.

    C'è un modo per aggirare questo problema?


    Edit: sto leggendo che dovrei usare "BindingFlags.NonPublic" e "BindingFlags.Instance flags"

    codice:
    FieldInfo[] fields = myType.GetFields(
                             BindingFlags.NonPublic| 
                             BindingFlags.Instance);
    

    Ultima modifica di RayanHawkins; 04-05-2018 a 15:22

  7. #7
    Moderatore di ASP.net L'avatar di djciko
    Registrato dal
    Nov 2002
    Messaggi
    6,886
    uhm...

    scusa se metti una cosa dentro il viewbag cosi'

    codice:
    public class StudentController : Controller
    {
        IList<Student> studentList = new List<Student>() { 
                    new Student(){ StudentID=1, StudentName="Steve", Age = 21 },
                    new Student(){ StudentID=2, StudentName="Bill", Age = 25 },
                    new Student(){ StudentID=3, StudentName="Ram", Age = 20 },
                    new Student(){ StudentID=4, StudentName="Ron", Age = 31 },
                    new Student(){ StudentID=5, StudentName="Rob", Age = 19 }
                };
    
    
        public ActionResult Index()
        {
            ViewBag.TotalStudents = studentList.Count();
            return View();
        }
    }

    poi non puoi leggerla con:

    <label>Total Students:</label> @ViewBag.TotalStudents

    ?

  8. #8
    Se faccio la costruzione tutto in una pagina si, nessun problema.

    Il problema è che gli elementi che mi servono vengono da una "viewbag" creata in altre pagine e trasportata con la "session", ed evidentemente questo passaggio rende privati i suoi elementi.

    Il metodo "BindingFlags.NonPublic" funziona, ma crea una variabile incasinatissima e non ho idea di dove andare a pescare gli elementi che mi servono.

    Continuo a studiare il problema...

  9. #9
    Ok risolto... anziché portarmi dietro la "viewbag", mi sono portato dietro tutte e 24 le liste dei valori che mi servivano

    codice:
    @model PagedList.IPagedList<RegistroPrivacy.Models.RPTrattamento>
    @using PagedList.Mvc;
    @using SocietaModelProperties;
    
    
    @{
        ViewBag.Title = SocietaModelProperties.ricercaTratt;
    	List<int> myListaId = new List<int>();
    	List<string> myListaSocieta = new List<string>();
    	List<string> myListaFunzioneAziendale = new List<string>();
    	List<string> myListaAttivita = new List<string>();
    	List<string> myListaDescrizione = new List<string>();
    	List<string> myListaFinalita = new List<string>();
    	List<string> myListaCategoriaDati = new List<string>();
    	List<string> myListaDati = new List<string>();
    	List<string> myListaCategoriaInteressati = new List<string>();
    	List<string> myListaBaseGiuridica = new List<string>();
    	List<string> myListaCategoriaDestinatari = new List<string>();
    	List<string> myListaTermineCancellazione = new List<string>();
    	List<string> myListaTipo = new List<string>();
    	List<string> myListaApplicativiCorrelati = new List<string>();
    	List<string> myListaResponsabile = new List<string>();
    	List<string> myListaResponsabileProtezione = new List<string>();
    	List<string> myListaRappresentanteUe = new List<string>();
    	List<string> myListaContattiContitolare = new List<string>();
    	List<string> myListaDescrizioneSicurezza = new List<string>();
    	List<string> myListaDescrizioneRischio = new List<string>();
    	List<string> myListaDataBreach = new List<string>();
    	List<string> myListaPaeseOrgDestinatario = new List<string>();
    	List<string> myListaPaeseOrgRicevente = new List<string>();
    	List<string> myListaGaranzie = new List<string>();
    	List<string> myListaNote = new List<string>();
    }
    
    [...]
    
    @{temp2 = item.InformazioniAttivita.FunzioneAziendale;}
    										@{myListaFunzioneAziendale.Add(temp2);}
    										@{Session["listaFunzioneAziendale"]= myListaFunzioneAziendale;}	
    
    
    										@{temp2 = item.InformazioniAttivita.Attivita;}
    										@{myListaAttivita.Add(temp2);}
    										@{Session["listaAttivita"]= myListaAttivita;}	
    
    
    										@{temp2 = item.InformazioniAttivita.Descrizione;}
    										@{myListaDescrizione.Add(temp2);}
    										@{Session["listaDescrizione"]= myListaDescrizione;}	
    
    
    										@{temp2 = item.InformazioniAttivita.Finalita;}
    										@{myListaFinalita.Add(temp2);}
    										@{Session["listaFinalita"]= myListaFinalita;}	
    
    
    										@{temp2 = item.InformazioniAttivita.CategoriaDati;}
    										@{myListaCategoriaDati.Add(temp2);}
    										@{Session["listaCategoriaDati"]= myListaCategoriaDati;}	
    
    
    										@{temp2 = item.InformazioniAttivita.Dati;}
    										@{myListaDati.Add(temp2);}
    										@{Session["listaDati"]= myListaDati;}	
    
    
    										@{temp2 = item.InformazioniAttivita.CategoriaInteressati;}
    										@{myListaCategoriaInteressati.Add(temp2);}
    										@{Session["listaCategoriaInteressati"]= myListaCategoriaInteressati;}	
    
    
    										@{temp2 = item.InformazioniAttivita.BaseGiuridica;}
    										@{myListaBaseGiuridica.Add(temp2);}
    										@{Session["listaBaseGiuridica"]= myListaBaseGiuridica;}	
    
    
    										@{temp2 = item.InformazioniAttivita.CategoriaDestinatari;}
    										@{myListaCategoriaDestinatari.Add(temp2);}
    										@{Session["listaCategoriaDestinatari"]= myListaCategoriaDestinatari;}	
    
    
    										@{temp2 = item.InformazioniAttivita.TermineCancellazione;}
    										@{myListaTermineCancellazione.Add(temp2);}
    										@{Session["listaTermineCancellazione"]= myListaTermineCancellazione;}	
    
    
    										@{temp2 = item.InformazioniAttivita.Tipo;}
    										@{myListaTipo.Add(temp2);}
    										@{Session["listaTipo"]= myListaTipo;}	
    
    
    										@{temp2 = item.InformazioniAttivita.ApplicativiCorrelati;}
    										@{myListaApplicativiCorrelati.Add(temp2);}
    										@{Session["listaApplicativiCorrelati"]= myListaApplicativiCorrelati;}	
    
    
    										@{temp2 = item.SoggettiPartecipanti.Responsabile;}
    										@{myListaResponsabile.Add(temp2);}
    										@{Session["listaResponsabile"]= myListaResponsabile;}	
    
    
    										@{temp2 = item.SoggettiPartecipanti.ResponsabileProtezione;}
    										@{myListaResponsabileProtezione.Add(temp2);}
    										@{Session["listaResponsabileProtezione"]= myListaResponsabileProtezione;}	
    
    
    										@{temp2 = item.SoggettiPartecipanti.RappresentanteUe;}
    										@{myListaRappresentanteUe.Add(temp2);}
    										@{Session["listaRappresentanteUe"]= myListaRappresentanteUe;}	
    
    
    										@{temp2 = item.SoggettiPartecipanti.ContattiContitolare;}
    										@{myListaContattiContitolare.Add(temp2);}
    										@{Session["listaContattiContitolare"]= myListaContattiContitolare;}	
    
    
    										@{temp2 = item.DescrizioneMisure.DescrizioneSicurezza;}
    										@{myListaDescrizioneSicurezza.Add(temp2);}
    										@{Session["listaDescrizioneSicurezza"]= myListaDescrizioneSicurezza;}	
    
    
    										@{temp2 = item.DescrizioneMisure.DescrizioneRischio;}
    										@{myListaDescrizioneRischio.Add(temp2);}
    										@{Session["listaDescrizioneRischio"]= myListaDescrizioneRischio;}	
    
    
    										@{temp2 = item.DescrizioneMisure.DataBreach;}
    										@{myListaDataBreach.Add(temp2);}
    										@{Session["listaDataBreach"]= myListaDataBreach;}	
    
    
    										@{temp2 = item.TrasferimentoDati.PaeseOrgDestinatario;}
    										@{myListaPaeseOrgDestinatario.Add(temp2);}
    										@{Session["listaPaeseOrgDestinatario"]= myListaPaeseOrgDestinatario;}	
    
    
    										@{temp2 = item.TrasferimentoDati.PaeseOrgRicevente;}
    										@{myListaPaeseOrgRicevente.Add(temp2);}
    										@{Session["listaPaeseOrgRicevente"]= myListaPaeseOrgRicevente;}	
    
    
    										@{temp2 = item.TrasferimentoDati.Garanzie;}
    										@{myListaGaranzie.Add(temp2);}
    										@{Session["listaGaranzie"]= myListaGaranzie;}	
    
    
    										@{temp2 = item.NoteLavoro.Note;}
    										@{myListaNote.Add(temp2);}
    										@{Session["listaNote"]= myListaNote;}

    Pensavo che avrei avuto problemi di performance con tutte queste liste, sia in lato view che in lato controller con i pure i cicli... e invece funziona cmq istantaneamente... che culo

  10. #10
    Moderatore di ASP.net L'avatar di djciko
    Registrato dal
    Nov 2002
    Messaggi
    6,886
    ..se funziona, ok

    non e' proprio il massimo dell'architettura ma ... basta che funzioni (per ora)

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.