0

I have a page that on the right side displays a log-in form from a PartialView, when the user submits their credentials, a jQuery $ajax calls a method in the controller to verify that the user exists otherwise is null.

Please point out what I am doing incorrectly and help me understand what is that I need to change or add to make it work, currently I cannot see the value of userid or password being passed to the action method.

I can see the message on the page though: "The user name or password provided is incorrect." But what is the point, somehow the values are not being passed.

Here are the complete examples of my code:

Index.cshtml

<div id="YourOrder_Login">
@if (!User.Identity.IsAuthenticated)
{
    <div class="YourOrder_loginForm">
        <div class="YourOrder_loginArea" style="position:relative;">
            @{Html.RenderAction("ShoppingCartLogin", "ShoppingCart");}
        </div>
    </div>
} else {
    <div class="YourOrder_addressArea" style="position:relative;">
        @{Html.RenderAction("ShoppingCartShippingAddress", "ShoppingCart");}
    </div>
}
</div> 

ShoppingCartLogin (PartialView)

<div class="YourOrder__inputEmail">
<input id="YourOrder_MainLoginEmail" class="YourOrder_MainLoginEmail" name="UserName" type="text" 
tabindex="1" />   
</div>
<div>
<input id="YourOrder_MainLoginPassword" class="YourOrder_MainLoginPassword" name="Password" 
type="password" tabindex="2" />
</div>
<div class="container_btnsignin">
<button type="button" class="fancyButton YourOrder_signin" id="btnLogin" value="SignIn" 
name="Command" onclick="javascript: ShoppingCartLogin();">Sign In</button>

The jQuery

<script type="text/javascript">

function ShoppingCartLogin() {

    var userid = $(".YourOrder_MainLoginEmail").val();
    var password = $(".YourOrder_MainLoginPassword").val();
    var url = "/ShoppingCart/ShoppingCartLogin";

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: JSON.stringify({usr: userid, pwd: password}),//{ userId: userid, pass: password },
        cache: false,
        success: function (result) {
            if (result.success = "Invalid") {
                $('.YourOrder_loginError').css('visibility', 'visible')
                $('.YourOrder_loginError').slideDown().html('The user name or password provided is incorrect.');
            }
            else {
                $('.YourOrder_loginError').css('visibility', 'hidden')
                location.reload();
            }
        }
    });

}

The controller code

        [HttpPost]
    [AllowAnonymous]
    public ActionResult ShoppingCartLogin(string userId, string pass)
    {
            using (Entities db = new Entities())
            {
                var user = (from u in db.Users where u.Email == userId && u.Password == pass && u.IsActive select u).FirstOrDefault();

                if (user == null)
                {
                    //ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    //return View("ShoppingCartLogin");
                    //return Json(new { status = "success", message = "The user name or password provided is incorrect." }); 
                    return Json(new { error = "Invalid" });
                }


                    List<string> roles = new List<string>();
                    if (user.IsAdmin)
                    {
                        roles.Add("Admin");
                    }
                    if (user.IsOrdersAdmin)
                    {
                        roles.Add("Orders");
                    }
                    if (user.IsStoreAdmin)
                    {
                        roles.Add("Stores");
                    }

                    user.LastLoginDate = DateTime.Now;
                    db.SaveChanges();

                    FormsAuthentication.SetAuthCookie(user.ID.ToString(), true);
                    return View("ShoppingCartShippingAddress");

            }
        }

2 Answers 2

2

Your parameter names must be matched, so your json object could be something like this: {userId: userid, pass: password}

However logging in using an ajax call is not a right way in this scenario, because you need to reload the whole page to update your page with ShoppingCartShoppingAddress partialview. It would be easier to do that using a form submit.

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

1 Comment

The reason why I am using an ajax request to do the user verification method (shoppingcartlogin), is because the page uses a jquery accordion that, on the last "tab" has a submit button whilst the log-in is done on the first "tab". Having the two submit buttons was causing issues, because when I was clicking the submit on the login form, the logic for the last "tab" was being executed. Using the ajax request and a button type button was the way I worked around the issue. If you know a better practice way to do this, please let me know. I will be happy to give it a try.
1

you are doing two things wrong here.

1.Parameter Mismatch 2.data:Json.Stringify

try this code

<script type="text/javascript">



function ShoppingCartLogin() {

        var userid = "12";
        var password = "Hsakarp";
        var UrlP = "/Default/ShoppingCartLogin";

        $.ajax({
        cache: false,
        type: "POST",
        url: UrlP,
        data: { userId: userid, pass: password },
             success: function (data) {
                 $('#Load').html(data);
             },
             error: function (xhr, ajaxOptions, thrownError) {
                 alert('Error');
             }
     });
}
    }
</script>

---html--

<button id="call" onclick="ShoppingCartLogin()">Post Data</button>

<div id="Load"></div>

--SC--

<h2>ShoppingCartLogin</h2>

<h2>Hrllo from shopping cart</h2>


<h2>Hrllo from shopping cart</h2>

<h2>Hrllo from shopping cart</h2>

--Controller--

public ActionResult ShoppingCartLogin(string userId, string pass)
        {

            return View("ShoppingCartLogin");

        }

8 Comments

Thank you. Why when the userId and pass are passed, the routine on the else does not get executed? I do not get errors but the page does not display the {Html.RenderAction("ShoppingCartShippingAddress", "ShoppingCart");} and that is what the location.reload is supposed to do, correct? reload the page so when the code @if (!User.Identity.IsAuthenticated) runs, it then retrieves the @{Html.RenderAction("ShoppingCartShippingAddress", "ShoppingCart");}
have you checked what get passed into result.success and then if you sending a view to the Ajax result you need to load it into some html tag preferably div.Check for result.success and in else part change it $('#divId').html(result)
the result.success gets the value Valid, I checked this: else (result.success = "Valid"){$('.YourOrder_loginError').css('visibility', 'hidden') location.reload();$("#YourOrder_loginForm").css('display', 'none');$("#YourOrder_addressArea").css('visibility', 'visible');$("#YourOrder_addressArea").html(data)} I think I am not passing the other partial view correctly, I say this because the action method does not return that on success, it returns a different message only. How the other partial view be passed, rendered when result.success is valid?
from the action method, i pass this when positive: return Json(new { error = "Valid" });
for testing - create a new proj and execute the code and analyse
|

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.