indofraiser
indofraiser

Reputation: 1024

Querying SQL from MVC

Aim: I want to be able to press a submit button, such as:

<input type="submit" value="Login" class="btn btn-default" />

and run the below code and return some sort of result i.e. let the user in, or not.

Notes: Earlier I posted and resolved: Runtime error Javascript is undefined if that's any guide as I build up. (On the plus side Menus etc.. all working!)

User.cs

using System;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.ComponentModel.DataAnnotations;

namespace Login.BL
{
    public class User
    {
        public int UserID { get; set; }
        [Required]
        public int Username { get; set; }
        [Required]
        public int UserPassword { get; set; }

    }

    public class UserBusinessLogic
    {
        string conStr = ConfigurationManager.ConnectionStrings["mySQL"].ConnectionString;
        public int CheckUserLogin(User User)
        {
            //Check the user is valid!!!!
            using (SqlConnection conObj = new SqlConnection(conStr))
            {
                SqlCommand comObj = new SqlCommand("retrieveUserByNameAndPassword", conObj);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@Username", User.Username));
                comObj.Parameters.Add(new SqlParameter("@UserPassword", User.UserPassword));
                conObj.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }
}

Login.cshml

@using Orientation.Models
@model LoginViewModel
@{
    ViewBag.Title = "Log in";
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>  

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Login" class="btn btn-default" />
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Register as a new user", "Register")
                </p>
                @* Enable this once you have account confirmation enabled for password reset functionality
                    <p>
                        @Html.ActionLink("Forgot your password?", "ForgotPassword")
                    </p>*@
            }
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jquery")
}

<script>
    //$document.ready(function () {
    //    $("myModal").modal({
    //        backdrop: 'static',
    //    });
    //});

    $("login").click(function ()
    {
        var dataObject = {Username: $("#Username").val, Password:$("#Password").val};
        $.ajax({
            url:'url.action("Login","User)',
            type: "POST",
            data: dataObject,
            datatype:"json",
            success: function(result)
            {
                if(result.tostring()=="Success")
                {
                    alert(result);
                }
                else
                {
                    alert(result); 
                }
            },
            error: function(result)
            {
                alert("Error");
            }
        });
    })
    </script>

Upvotes: 1

Views: 58

Answers (1)

Shyju
Shyju

Reputation: 218852

First of all, your jQuery selector is wrong. There is no such element called login in your page. Give an id to your submit button so that you can use it as your jQuery selector.

<input type="submit" id="loginBtn" value="Login" class="btn btn-default" />

Now in your javscript, listen to the click on this button(Use the Id selector). Since your form elements are already in a form, you may simply serialize the form and send it.

$(function(){

  $("#loginBtn").click(function(e){

    e.preventDefault();
    var _form=$(this).closest("form");

    $.post(_form.attr("action"),_form.serialize(),function(response){

       if(reponse.Status==="Success")
       {
         alert("Valid user");
       }
       else
       {
         alert(response.Message);
       }
    });

  });

});

Now in your Login action method, call your custom method and use the return value of that to return a JSON object back to the client

[HttpPost]
public ActionResult Login(User user)
{       
   try
   {
     var bl=new UserBusinessLogic();
     var result = bl.CheckUserLogin(user);
     //based on the result return something
     if(result==1) //demo purpose. Change to match with what your code actually returns
     {
        return Json(new {Status="Success" });
     }
     return Json(new {Status==="Invalid", Message="Invalid user credentials" });
  }
  catch(Exception ex)
  {
      return Json(new {Status==="Valid", Message="Code crashed!.
                   Put a breakpoint in your action method and see what is happening" });
  }
}

Upvotes: 1

Related Questions