save variable without being "cleaned" when doing return view C #

1

I have a small problem, it turns out that I am doing two filters in my project (One by date and the other by company). The filter by date works perfect I change it by date and it filters well but that date that I send it I want it to be stored in a variable, when making the return view that date sent does not save it, "Clean the model" and I need That date will leave it fixed somewhere in my controller (That is not cleaned).

ScreenShot

Before the return view the date today1 has that data as datetime.

After the return view (With the code still running) The variable today1 is empty.

Code C #

public class CierreController : Controller
{

    MVELEntitiess cm = new MVELEntitiess();
    private string fecha = null;
    private DateTime today1 = DateTime.Today;// fecha actual, inicializada global, puesto que todos los metodos la usan, y posteriormente se le asigna una fecha que contenga datos
    private DateTime inicio;// fecha inicio/fin. inicializada global puesto que todos los metodos la utilizan para filtrar la cantidad de dias del mes que contiene datos
    private DateTime fin;
    private int[] graficodays;// en los ActionResult se llenara con la cantidad de dias del mes que contiene datos, pasados a un formato que recibe la libreria del grafico
    private decimal?[] valorgraficodiario; // en los ActionResult se llenara con el valor margen operativo para cada dia del mes convertidos a un formato para el grafico
    private NumberFormatInfo nfi = new CultureInfo("es-AR", false).NumberFormat; // le otorga el formato chileno a los valores y valores monetarios
    private NumberFormatInfo us = new CultureInfo("es-AR", false).NumberFormat; // Otorga el formato en - US
    public DateTime fechafiltroempresa;



    public ActionResult Cierre(FormCollection ddl1, string zonas, string empresas)// metodo ActionResult que llena toda la vista para ser mostrada por el navegador
    {

        fecha = ddl1["TextBox1"];
        if (fecha != null)
        {

            today1 = Convert.ToDateTime(fecha.ToString().Substring(3, 2) + "-" + fecha.ToString().Substring(0, 2) + "-" + fecha.ToString().Substring(6, 4));
            fechafiltroempresa = today1;
            // return RedirectToAction("NewMethod", "Cierre", new{today1});
        }

        double iny, ret, bal, ingr;

        string[] seriesgrafico = new string[1];

        seriesgrafico[0] = "Datos";
        cm.zona = "";
        cm.empresa = "";



        if (zonas == "norte")
        {
            // el filtro puede cambiarse, al modificar el "value" que retorna desde el html
            ViewBag.zona = " - Zona Norte ";

        }

        else if (zonas == "centro")
        {
            cm.zona = " - Zona Centro ";

        }
        else if (zonas == "sur")
        {
            cm.zona = " - Zona Sur ";

        }
        if (empresas == "Enel Generación")
        {
            cm.empresa = " - ENEL ";
        }

        return NewMethod(zonas, empresas, out iny, out ret, out bal, out ingr, seriesgrafico);
    }

    private ActionResult NewMethod(string zonas, string empresas, out double iny, out double ret, out double bal, out double ingr, string[] seriesgrafico)
    {
        cm.minimotecnico = minimoTecnico(today1, zonas, empresas);// minimo tecnico siempre debe ser el primer metodo en ser llamado, puesto que tambien obtiene la fecha a presentar en la vista
        cm.costomarginal = costoMarginal(today1, zonas, empresas);
        cm.ingresoscompania = ingresoCompania(today1, zonas, empresas);
        cm.costooperacional = costoOperacion(today1, zonas, empresas);
        ingr = ingresoTarifario(today1, zonas, empresas);
        cm.ingresotarifario = ingr.ToString("C", nfi);
        cm.margenoperativo = margenOperativo(today1, zonas, empresas);
        iny = inyecciones(today1, zonas, empresas);
        cm.inyecciones = iny.ToString("N", nfi);// el argumento "N" indica que es una cifra numerica y "nfi" es la variable que indica el pais de formato
        ret = retiros(today1, zonas, empresas);
        cm.retiros = ret.ToString("N", nfi);
        cm.inyeccionesVAL = inyeccionesValorizadas(today1, zonas, empresas);
        cm.retirosVAL = retirosValorizados(today1, zonas, empresas);
        cm.balance = balance(iny, ret);

        bal = balanceValorizados(today1, zonas, empresas);
        cm.balanceVAL = bal.ToString("C", us);


        cm.balanceReal = balanceReal(bal, ingr);

        cm.fechainicio = inicio.ToString("dd MMM yyyy", CultureInfo.CreateSpecificCulture("es-CL"));
        cm.fechafin = fin.ToString("dd MMM yyyy", CultureInfo.CreateSpecificCulture("es-CL"));
        cm.fechagrafico = today1.ToString("MMMM yyyy", CultureInfo.CreateSpecificCulture("es-CL"));
        cm.cantidaddias = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(graficodays);// depende de funcion margenOperativo
        cm.valordiario = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(valorgraficodiario);
        cm.fechapdf = today1;


        int[] valorestudio = new int[valorgraficodiario.Length];

        for (int i = 0; i < valorgraficodiario.Length; i++)
        {
            valorestudio[i] = 0;

        }
        cm.valorestudio = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(valorestudio);
        ViewBag.estudio = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(seriesgrafico);
        ViewBag.titulo = "Cierre" + cm.zona + "" + cm.empresa + "";
        ViewBag.titulopdf = "";// titulo que se mostrara en el pdf, esta vacio por que no debe mostrarse en el navegador solo en el pdf, puesto que se llenara en actionresult posterior


        return View("~/Views/Cierre/Cierre.aspx", cm);
    }

is MVC-2 (With aspx)

Any ideas? Here is the extract of my aspx code.

<div id="myModalFecha" class="modal fade" role="dialog">

            <div class="modal-dialog modal-sm" style="; left: 50%; top: 50%; margin-left: -140px; margin-top: -240px;">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Fecha</h4>


                        <div class="modal-body">

                            <form id="filtrosFormFecha" method="post" class="form-horizontal">

                                <div class="well row">
                                    <div class="form-group">
                                        <div>
                                            <h3 style="text-align: center; font-family: Univers Light; font-size: 18px; color: #073492;">Fecha:</h3>
                                            <%using (Html.BeginForm("Cierre", "Cierre"))
                                                {%>
                                            <div class="col-lg-12 col-sm-12" style="margin-top: 15px;">
                                                <asp:textbox id="TextBox1" name="TextBox1" runat="server"></asp:textbox>
                                                <div class="col-lg-2 col-xs-12" style="margin-top: 5px;">
                                                </div>
                                                <%-- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">--%>
                                                <%--<link rel="stylesheet" href="/resources/demos/style.css">--%>
                                                <%--<script src="https://code.jquery.com/jquery-1.12.4.js"></script>--%>
                                                <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
                                                <script>
                                                    $( function() {
                                                        $("[id*=TextBox1]").datepicker({dateFormat:'dd-mm-yy'});
            
                                                        // $("[id*=TextBox1]").datepicker({dateFormat:'dd-mm-yy'});
                                                    } );
                                                </script>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <center>
            <div class="form-group">

What I need basically is that this variable today1 is not cleaned or some way to save it.

    
asked by Joel Baez 17.07.2018 в 18:33
source

1 answer

1

If you want to keep the value of the variable once you have finished the request, you have to save it in session, or in a cookie. The variables declared in your controller are initialized and deleted with each request.

Saving it in session and recovering it from session would be the easiest. You can put this code in any method within your controller:

//Guardar el valor:
Session["today1"] = DateTime.Now;
//Recuperar el valor
var fechaEnSesion = Session["today1"];
    
answered by 18.07.2018 / 05:29
source