2016-03-02 106 views
1

目的:我希望能够按一个提交按钮,如:查询SQL从MVC

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

并运行下面的代码,并返回某种结果的,即让用户,或不。

注: 早些时候我张贴和解决:Runtime error Javascript is undefined如果这是任何指导,因为我建立。 (加方菜单等所有的工作!)

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> 

回答

1

首先,你的jQuery选择是错误的。在您的页面中没有这样的元素,称为login。给你的提交按钮提供一个id,这样你就可以使用它作为你的jQuery选择器。

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

现在在你的javscript中,听听点击这个按钮(使用Id选择器)。由于您的表单元素已经在表单中,因此您可以简单地序列化表单并发送它。

$(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); 
     } 
    }); 

    }); 

}); 

现在,在您登录的操作方法,请拨打您的自定义方法和使用的返回值来返回一个JSON对象返回给客户端

[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" }); 
    } 
} 
+0

哎呀。那么这将无济于事。我明天会修改。 – indofraiser

+1

你是什么意思,这没有帮助。 – Shyju

+0

我的意思是我没有帮助自己,道歉。我起床后几个小时就会看看。 – indofraiser