My javascript function does not call controller action

Asked

Viewed 3,617 times

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, "");
        }

    });
}

and 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 turns out that when I click the button to log in, nothing happens. There is no error and I realize that the form is sent, but it does not call the JS function and therefore 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>

A question. When I changed the action value in the 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/Minha_action" or can that be the case? For in another example in another company that I was, my friend did so as above and worked and gives me the error.

I put in Fidlle and gave me that mistake 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'}"}

2 answers

3

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

Put this after function implementation loginUsuario():

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

    loginUsuario();
});

The above section will prevent the standard behavior of the form and will call the function needed to send the data to your back-end.

  • added javascript libraries to my cshtml and continues to give the error: $ is not defined

  • Your jQuery is installed?

  • yes: <script src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script> <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script> <script src="@Url.Content("~/Scripts/jquery-2.1.0.js")"></script> <script src="@Url.Content("~/Scripts/jquery-2.1.0.min.js")"></script> <script src="@Url.Content("~/Scripts/jquery-migrate-1.2.1.js")"></script> <script src="@Url.Content("~/Scripts/jquery-migrate-1.2.1.min.js")"></script> <script src="@Url.Content("~/Scripts/jquery-ui.js")"></script> <script src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>

  • Here’s the thing, I moved the Home/Home.js line of script to the end and I didn’t get the bug anymore. I didn’t know that until then. But still not in my way.

  • What error the console displays, @pnet?

3


Try switching your method signature in Controller to simple types, and enter the POST annotation explicitly:

Example:

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

And to create the JSON object, not at all a spin, just do so:

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

And in the ajax call change to that:

$.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 make the call in the way @Guilhermeoderdenge quoted in your reply, to avoid the POST pattern of form.

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

EDIT (responding 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>
  • @pnet, remove the onclick of the buttons and the action of form, and maintain a button of type="submit", that will trigger the event submit, jQuery is already watching the submit.

  • So, I did as Fernando told me, but still does not enter the Jquery function, because I put an Alert() right at the beginning and still it does not fire

  • @pnet, could post your code client in the jsFidlle, so that we can identify the problem more easily?

  • @pnet, I made an example here and is calling the function.

  • With me it says $ is not set. Why does it give this error? The error gives in this line: $('form'). on('Submit', Function (and) {

  • @pnet jsFiddle does not support server-side language.

  • I removed everything you do from the server. I just made html simple and js. That worked.

  • Fernando, I copied everything in yours and gives the same error. I made the copy directly from Fidlle and I went there. It keeps giving the error.

  • Keeps giving the same error: $ is not defined

  • I found the bug by Fidlle. Missing add the js library, 1.10.1 or higher, I don’t know.

  • @pnet, is that you are not importing Jquery, I thought you were already using jQuery. Because in your code there is the following: JQuery.parseJSON

  • 1

    I think it was browser cache. I restarted the browser and it worked, that is, entered the function and called the controller function. Only that gave this error that I am checking the why: The underlying Provider failed on Open.

  • @pnet, dai is already a query error in the Entity Framework, as cited here

  • Exactly, it was pwd that was not passed in the EF connection by web.config. Just one question, even when we set up Entity and saved the password, wasn’t it meant to appear on the,config web? Just for the record. It’s already solved

  • @pnet, did not understand your question, which Entity? which password?

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.