Home > other >  Get value from View to another controller
Get value from View to another controller

Time:03-15

i've a unique controller where i control it all my views so from here i've got a problem. After to send data to do login i need obtain a value sended. For example, i've this controller: HomeController, in this controller i've four ActionResult:

ActionResult Index

ActionResult Login

ActionResult Cuotas

ActionResult LogOff

So, when the user login i need obtain here username to verify is already connected from my DB

HomeController:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(string uname, string psw)
    {
        try
        {
            ViewData["uname"] = uname;
            ViewData["psw"] = psw;

            ConexionSQL sql = new ConexionSQL();
            var usuario = sql.login(uname, psw);
            var existencia = sql.usuarioOCobrador(uname, psw);

            if (existencia[0].usuario == "USUARIO")
            {
                var caracteres = Convert.ToString(psw);
                var pruebaUsuario = sql.datos(uname);


                if (pruebaUsuario[0].clave == caracteres)
                {
                    return View("Cuotas", usuario);
                }
                else
                {
                    ViewBag.Contra = "Contraseña incorrecta.";
                }
            }
            else if (existencia[0].usuario == "COBRADOR")
            {
                return RedirectToAction("Cuotas", "Home", usuario);
            }
            else
            {
                ViewBag.Usu = "Usuario incorrecto o usted no tiene los permisos para ingresar al sistema. Comuníquese con el área pertinente o el Departamento de Sistemas.";
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        return View("Index");
    }

        public ActionResult LogOff(string uname)
        {
            ConexionSQL conexionSQL = new ConexionSQL();
            conexionSQL.updateConectado(uname, false);
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Cuotas()
    {
        ConexionSQL sql = new ConexionSQL();
        string uname = string.Empty;
        string psw = string.Empty;

        //Get your ViewData variables here
        if (ViewData["uname"] != null)
        {
            uname = Convert.ToString(ViewData["uname"]);
        }

        if (ViewData["psw"] != null)
        {
            psw = Convert.ToString(ViewData["psw"]);
        }
        var usuario = sql.datosCob(uname);
        if (usuario[0].conectado == false)
        {
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return RedirectToAction("Cuotas", "Home");
        }
    }
}

Index View, here is the login:

        <form  onsubmit="return control()" method="post" action="@Url.Action("Login", "Home")">
            <div >
                <span onclick="document.getElementById('id01').style.display='none'"  title="Cerrar">&times;</span>
                <img src="~/Images/00.png" alt="Logo" />
            </div>
            <div >
                <label for="uname"><b>Usuario:</b></label>
                <input type="text" id="uname" placeholder="Ingrese usuario..." name="uname" onkeypress="return soloLetras(event)"/>

                <label for="psw"><b>Contraseña:</b></label>
                <input type="password" id="psw" placeholder="Ingrese contraseña..." name="psw" onkeypress="return soloNumeros(event)"/>

                <button type="submit">Iniciar sesión</button>
            </div>
        </form>

But uname always is null, whats wrong with my code?

enter image description here

CodePudding user response:

If I understand correctly, you need to get your uname that you first post to your Login method and then you need this variable your Cuotas method on the same request when the form is submitted? If that is the case then you have to use Session to persist your variables from one Controller action to another. Your form action is Login method and not Cuotas method so your FormCollection will always be null. So in your case, it would look like:

    public ActionResult Login(string uname, string psw)
    {
        Response.AppendHeader("Cache-Control", "no-store");
        try
        {
            //Set your variables here to passed to next action
            Session["uname"] = uname;
            Session["psw"] = psw;

            ConexionSQL sql = new ConexionSQL();
            var usuario = sql.login(uname, psw);
            var existencia = sql.usuarioOCobrador(uname, psw);

            if (existencia[0].usuario == "USUARIO")
            {
                var caracteres = Convert.ToString(psw);
                var pruebaUsuario = sql.datos(uname);


                if (pruebaUsuario[0].clave == caracteres)
                {
                    sql.updateConectado(uname, true);
                    return RedirectToAction("Cuotas", "Home");
                }
                else
                {
                    ViewBag.Contra = "Contraseña incorrecta.";
                }
            }
            else if (existencia[0].usuario == "COBRADOR")
            {
                sql.updateConectado(uname, true);
                return RedirectToAction("Cuotas", "Home");
            }
            else
            {
                ViewBag.Usu = "Usuario incorrecto o usted no tiene los permisos para ingresar al sistema. Comuníquese con el área pertinente o el Departamento de Sistemas.";
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        return View("Index");
    }

And you can get them in your Cuotas method like this:

    public ActionResult Cuotas()
    {
        ConexionSQL sql = new ConexionSQL();
        string uname = string.Empty;
        string psw = string.Empty;
        //Get your ViewData variables here
        if (Session["uname"] != null)
        {
          uname = Convert.ToString(Session["uname"]);
        }

        if (Session["psw"] != null)
        {
          psw = Convert.ToString(Session["psw"]);
        }
        var usuario = sql.datosCob(uname);
        if (usuario[0].conectado == false)
        {
            return RedirectToAction("Index");
        }
        else
        {
            return View("Cuotas");
        }
    }
  • Related