Problem redirecting view from another controller

0

This is my sending function, I have taken from examples that I have seen in this forum

function enviarDatos() {
        var params = {
            valor1 : $("#usuario").val(),
            valor2 : $("#clave").val()
        };

        $.ajax({
            url: this.href,
            type: "post",
            data: params,
            success: function (result) {
                if (result.success) {
                    //Refresh
                    window.location.reload();
                }
            }
        });

    }

This is how I get it in the controller the debug goes through the RedirectToAction and ends the method, but does not redirect I have not found help regarding this issue in which I have no experience

public ActionResult Index(string usuario, string pass)
    {
        try
        {                
            usuario = Request.Form.Get("valor1");
            pass = Request.Form.Get("valor2");
            bool valida = true;
           //Usuario usu = new Usuario();
           //valida = usu.ReadAll(usuario, pass); 

            if (valida)
            {
                return RedirectToAction("Inicio", "Inicio");
            }
    
asked by Bastian Salazar 10.05.2017 в 18:25
source

2 answers

1

Correcting the functions presented in the problem, I was able to solve the problem, first the method that it sends to the server:

    function enviarDatos() {
            var params = {
                valor1 : $("#usuario").val(),
                valor2 : $("#clave").val()
            };

            $.ajax({
                 type: "POST",
                 url: '@Url.Action("Index", "Home")',
                 content: "application/json; charset=utf-8",
                 dataType: "json",
                 data: params,
                 success: function (respuesta) {
                       if (respuesta.model == '1') {
                          location.href = "Home/Inicio/";
                      } else if (respuesta.model == '2'){
                        Alert.render('El usuario ingresado no está registrado');
                      } else if (respuesta.model == '3'){
                        Alert.render('La clave ingresada es incorrecta');
                      } else {
                         Alert.render('Error: Ocurrió un problema en el método "Validar Usuario"');
                      }
                },
                  error: function (xhr, textStatus, errorThrown) {
                     Alert.render('Error: No se pudo cargar método "Validar Usuario"');
                  }
               });
}

Then modify the method on the server

[HttpPost]
    public JsonResult Index(FormCollection collection)
    {
        try
        {
            //obtiene valores de usuaio y clave del FormCollection
            string usuario = collection["Usuario"].ToString();
            string pass = collection["Clave"].ToString();
            UsuarioDAL dal = new UsuarioDAL();
            //solicita validacion del usuario
            int valida = dal.ValidarUsuario(usuario, pass);
            int model = 0;
            if (valida == 1)
            {
                model = 1;//usuario y clave correctos                    
            }
            else if (valida == 3)
            {
                model = 2;//El usuario ingresado no está registrado
            }
            else if (valida == 2)
            {
                model = 3;//La clave ingresada es incorrecta
            }

            //valida que el metodo de validacion no venga como un "catch"
            var result = new { Success = true, Message = "Succes Message", model };
            return Json(result, JsonRequestBehavior.AllowGet);


        }catch(Exception e)
        {
            var result = new { Success = false, Message = "Error Message" };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }//fin IniciarSesion()

By using the answers with AJAX, you can have better control of the status of the query

    
answered by 20.02.2018 / 17:04
source
0

The new page you are requesting is not reloaded for the simple fact that you are not doing a redirect.

AJAX serves to avoid refreshing the page and upload content to the current page.

Now what you need to do is%% of the form in ASP .NET MVC you can do the following

Vista index: (your view where you have the ajax).

<body>
  <!--form action="@Url.Action("Vista","Controlador")" method="post"-->
  <form action="@Url.Action("Index","Home")" method="post">
    <input type="text" name="Usuario" placeholder="Usuario">
    <input type="text" name="Password" placeholder="Contraseña">
    <button type="submit">Entrar</button>
  </form>
</body>
<!-- He quitado el ajax ya que no voy a recargar la vista en esta url -->

Home Controller

//get
public ActionResult Index()
{
  return View();
}
[HttpPost]//se recibe el post con la informacion del logeo
public ActionResult Index(ModeloLogin model)
{
  //validando la informacion
  if (valida)
  {
    return RedirectToAction("Inicio", "Inicio");
    //si la informacion es valida redireccionamos a la nueva vista
  }
  return View();//volvemos a la vista index
}

ModelLogin // is required to parse the information that entered the input.

public class ModeloLogin
{
  //variables para cargar los datos enviados por el usuario
  public String UserName { get; set; }
  public String Password { get; set; }
}
  

NOTE:

     
  • To help you understand the concept of MVC in ASP .NET   MVC review    link
  •   
  • Or if you prefer something more visual the good fredyfx workshop link
  •   
        
    answered by 10.05.2017 в 19:48