My javascript function does not call action controller

3

I have this javascript function.

function loginUsuario(){

    alert();

    if(($('#txtUsuario').val() != "") && ( $("#txtSenha").val() != ""))
        resultado = JQuery.parseJSON('{"Usuario": "' + $('#txtUsuario').val() + '", "Senha": "' + $("#txtSenha").val() + '}');
    else
        return;

    $.ajax({

        url: '/Home/loginUsuario',
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ loginUsuario: resultado }),
        success: function (data) {

            alert('Login realizado com sucesso!!');
        },
        error: function (error) {

            loading(0, "");
        }

    });
}

I have this action in the controller still under development

public ActionResult loginUsuario(LoginUsuario loginUsuario)
        {
            V99_WEB_QAEntities db = new V99_WEB_QAEntities();

            EncriptyDecripty decripta = new EncriptyDecripty();

            try
            {
                var resultado = (from log in db.T_Usuario
                                 where log.Login == loginUsuario.Usuario && decripta.Decrypt(log.Pswd) == loginUsuario.Senha
                                 select new { log.Nome }).FirstOrDefault();
            }
            catch (Exception ex)
            {
                string erro = ex.Message;
            }

            return View(loginUsuario);
        }

It happens that when I click the button to log in, nothing happens. It does not give an error and I realize that the form is sent, but it does not call the JS function and consequently does not call the action. What else should I do? Below is my CSHTML.

<form method="post" action="@Action" id="frmLogin">
                <table style="margin-top:10px;">
                    <tr>
                        <td>
                            Usuário:
                        </td>
                        <td>
                            <input type="text" name="txtUsuario" id="txtUsuario" maxlength="20" class="" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Senha:
                        </td>
                        <td>
                            <input type="password" name="txtSenha" id="txtSenha" maxlength="10" class="" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @*<input type="submit" name="btnEntrar" id="btnEntrar" value="Entrar" onclick="loginUsuario();"/>*@
                            <button name="btnEntrar" id="btnEntrar" value="Entrar" onclick=" loginUsuario();">Entrar</button>
                        </td>
                    </tr>
                </table>
            </form>

One question. When I changed the value of the action in form, it gave me this error:

Compiler Error Message: CS0118: 'System.Action' is a 'type' but is used like a 'variable'

Source Error:


Line 19:         <fieldset>
Line 20:             @*<legend>Informe seus dados</legend>*@
Line 21:             <form method="post" action="@Action" id="frmLogin">
Line 22:                 <table style="margin-top:10px;">
Line 23:                     <tr>

Should I keep action="/ Home / My_Action" or can it be this way? For another example in another company that I was, my friend did so as above and worked and with me gives me the error.

I put it in Fidlle and it gave me that error there:

{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x2145890>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0xfcc210>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x2145890>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0xfcc350>, 'help_text': '', 'name': 'js_wrap'}"}
    
asked by anonymous 23.04.2014 / 15:38

2 answers

3

Try changing the signature of your method in the Controller for simple types, and insert the POST annotation explicitly:

Example:

[HttpPost]
public ActionResult loginUsuario(string Usuario, string Senha)

And to create the JSON object, not at all a spin, simply do this:

resultado = {"Usuario": $('#txtUsuario').val(), "Senha": $("#txtSenha").val()});

And in the ajax call change to this:

$.ajax({
    url: '/Home/loginUsuario',
    datatype: 'json',
    contentType: "application/json; charset=utf-8",
    type: "POST",
    data: JSON.stringify(resultado), // passe simplesmente o JSON serializado em string
    success: function (data) {
        alert('Login realizado com sucesso!!');
    },
    error: function (error) {
        loading(0, "");
    }
});
  

Also call in the mode that @GuilhermeOderdenge quoted in your answer to avoid POST of form .

$('form').on('submit', function(e) {
    e.preventDefault();    
    loginUsuario();
});

EDIT (replying to comment)

Your form would look like this:

 <form method="POST" id="frmLogin">
            <table style="margin-top:10px;">
                <tr>
                    <td>
                        Usuário:
                    </td>
                    <td>
                        <input type="text" name="txtUsuario" id="txtUsuario" maxlength="20" class="" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Senha:
                    </td>
                    <td>
                        <input type="password" name="txtSenha" id="txtSenha" maxlength="10" class="" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" name="btnEntrar" id="btnEntrar" value="Entrar"/>
                    </td>
                </tr>
            </table>
        </form>
    
23.04.2014 / 15:46
3

When you submit the form, you should call the loginUsuario() function. Are you doing this?

Put this after the implementation of the loginUsuario() function:

$('form').on('submit', function(e) {
    e.preventDefault();

    loginUsuario();
});

The above excerpt will prevent the default behavior of the form and will call the required function to send the data to your back end.

    
23.04.2014 / 15:43