Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
Get value from View to another controller

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 class="modal-content animate" onsubmit="return control()" method="post" action="@Url.Action("Login", "Home")">
            <div class="imgcontainer">
                <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Cerrar">&times;</span>
                <img src="~/Images/00.png" alt="Logo" class="avatar"/>
            </div>
            <div class="container">
                <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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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");
        }
    }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda