0

I am kind of new to jquery ajax. I am tring to learn client side jquery validation without using the DataAnnotations. when I press the login button the page refreshes doesn't post to the controller's Login(User x) method using the ajax post. I am not a expert any advice and suggestions will be greatly appreciated.

My model

public class User
{
    public String UserName { get; set; }
    public String Password { get; set; }
}

My controller

public class LoginController : Controller
{
  [HttpPost]
    public bool Login(User x)
    {
        return false;
    }

    public ActionResult LoginTst()
    {
        return View();
    }
}

The view is LoginTst & the script

$(document).ready(function()
    {
        $("#signin").click(function ()
        {
           
                $("#loginForm").validate({
                    rules: {
                        UserName: {
                            required: true,
                            minlength: 2,
                            maxlength: 15
                        },
                        Password: {
                            required: true,
                            minlength: 5,
                            maxlength: 18
                        }
                    },
                    messages: {
                        UserName: {
                            required: "username req",
                            minlength: "user is small",
                            maxlength: "user is long"
                        },
                        Password: {
                            required: "pass req",
                            minlength: "pass is small",
                            maxlength: "pass is long"
                        }
                    },
                    submitHandler: function (form) {
                        var form = $('#loginForm');
                        $.ajax({
                            cache: false,
                            async: true,
                            type: "POST", 
                            url: form.attr('Login'), // the action it 
                            data: form.serialize(),
                            success: function (data) {
                                if (data == false) {
                                    alert("Username doesn't exist");
                                }
                            }
                        });
                    }

                });

            });

        
    });
<form action="" name="loginForm" id="loginForm">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Username" id="UserName" name="UserName">
        </div>
        <div class="form-group">
          <input type="password" class="form-control" placeholder="Password" id="Password" name="Password">
        </div>
        <div class="form-group">
        <button class="btn btn-warning btn-block" type="submit" id="signin">login</button>
        </div>   
     </form>

What am i doing wrong?

1
  • your action isn't set to anything. Commented Nov 29, 2016 at 17:24

2 Answers 2

1

The problem is that your action is not set. You could set it manually or you can wrap your input fields with an Html.BeginForm. The latter allows you to reference your controller as well as a method on your controller without being worried about the relative path.

Here is an example:

@using (@Html.BeginForm("Login", "Login", FormMethod.Post, new {@id="loginForm"}))
{   
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Username" id="UserName" name="UserName">
    </div>
    <div class="form-group">
      <input type="password" class="form-control" placeholder="Password" id="Password" name="Password">
    </div>
    <div class="form-group">
      <button class="btn btn-warning btn-block" type="submit" id="signin">login</button>
    </div>  
}

Of course, you could use HTML Helpers for the input controls inside the using block as well.

You also need to update your submitHandler to pull in the action as generated by the form helpers:

submitHandler: function(form) {
  var form = $('#loginForm');
  $.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'), // the action as defined in the <form> 
    data: form.serialize(),
    success: function(data) {
      if (data == false) {
        alert("Username doesn't exist");
      }
    }
  });
}

You can find a working dotnetfiddle example here: https://dotnetfiddle.net/kRfSnh

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for your reply but I am tring to call the ajax post in my script
@abarthelot Updated my answer. It's still related to the Action attribute but also needs to be updated in your submitHandler.
Sorry for the late reply, I tried your way and the validation stops working
no worries. there were two syntax errors: missing an '@' before the using statement and missing a quote for when declaring the login form ID.
I fixed them when i tried it but it's still not working :(
|
1

You're setting URL to form.attr('Login'), but in your HTML, form does not have a "Login" attribute.

What you probably want to do is set the action on the form (to the url you want), and change the url in the javascript to use form.attr('action').

3 Comments

I added action="@Url.Action("Login", "LoginController")" in the form and the validation doesn't work. when i remove it the validation works again, i even tried $("#loginForm").submit(function (e) { e.preventDefault(e); and added the ajax post here}); this calls the action method in the controller but refreshes the page
Try changing "LoginController" to just "Login". Did you also change your javascript from url: form.attr('Login') to url: form.attr('action')?
Yes i did and i checked in the debugger it calls the action method i want but it is not using the submitHandler, it is using the form default submit which calls the action method from 'action' attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.