1

我正在从事 mvc3 和 wcf 服务中的会计项目。我正在使用 javascript、ajax 进行表单验证。我用javascript编写验证表单的代码。但我的 javascript 警报没有显示给 user.although 我在 brwoser 中启用了 javascript。当我调试代码时,会显示 javascript 警报,但如果提交表单则不调试代码,则不会向我显示用于验证的警报消息。

以下是 mvc3 中的表单代码

@model CBS.Models.AccntBD

@{
ViewBag.Title = "AccCode";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AccCode</h2>

<div>

@using (Html.BeginForm())
{
<table class="tablestyle">
    <tr>
<td>   
<label>Account Code</label>
</td>
<td>
              <input type="text" id="AcCode" name="AcCode" maxlength="10" placeholder="Account     Code" autofocus="true" class="required" />

@Html.ValidationMessageFor(m => m.AcCode)
</td>
</tr>
<tr>
<td>
 <label>Description</label>
</td>
<td>
   <input type="text" id ="Descrip" name="Descrip" maxlength="150" placeholder="Desription..."     class="Descrip"/>
              @Html.HiddenFor(m=>m.Descrip) 
            @Html.ValidationMessageFor(m => m.Descrip)
</td>
</tr>
   <tr>
   <td>
   <span>
    <input type="submit" value="Cancel" onclick="Cancel()" />
   </span>           
          <span>
         <input type="submit" id="sve" name="action" value="Save" />
        </span>
         <span>
         <input type="submit" id="edi" value="Edit" name="action"/>             
        </span>
   <span>
    <input type="submit" value="Delete" id="del" name="action"/>
   </span>
        </td>
       <td>
   </td>
         </tr>  
   <tr>
   <td>       
                           @ViewData["result"]
              </td>
   <td>
   @Html.ValidationMessage("CustomError")

   </td>
   </tr>
</table>     
    }
    </div>
@section PageScripts{
<script src="/Scripts/test.js" type="text/javascript"></script>

}

下面是我的 test.js 文件代码

  $('#sve').click(function () {
    //e.preventDefault();
    var isValid = validateForm();
    if (isValid) {

        //***********************CODE TO SAVE DATA IN DATABASE***********************************
        var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
        $.ajax({
            url: '/Home/Save?action=Sve',
            type: "POST",
            data: JSON.stringify(person),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                //   $('#message').html('Record saved successfully' + result).fadeIn();
                alert("Record saved successfully");
            },
            error: function () {
                //    $('#message').html('Error Occurred').fadeIn(); 
                alert("Record not saved successfully");
            }
        });
    }
    else
        return false;

});  //end button clcik function

function GetCodeData(Str) {

    var p = {
        StrSql: Str

    };
    $.ajax({
        url: '/Home/GetGenVal',
        type: 'POST',
        // contentType: 'application/x-www-form-urlencoded',
        dataType: "JSON",
        contentType: "application/json; charset=utf-8",
        processData: false,
        crossDomain: false,
        traditional: true,
        data: JSON.stringify(p),
        cache: false,
        //   success: callback
        success: function (data) {
            //$("#Descrip").val(data);
            //  ResSubCode = data;
            strRes = null;
            strRes = data;
            return strRes;
        }

    });
}


 function validateForm() {
    //==================CHCK EMPTY OR NULL OF ACCOUNT CODE FIELD===========================
    if ($('#AcCode').val().trim().length === 0) {
        alert('Must enter Account Code');
        $('#AcCode').focus();
        return false;
    } //end if
    //==================CHCK EMPTY OR NULL OF DESCRIPTION FIELD===========================
    if ($('#Descrip').val().trim().length === 0) {
        alert('Must enter Description');
        $('#Descrip').focus();
        return false;
    } //end if

    //==========================CHEK ACCOUNT CODE DIGITS=============================================
    subA = $('#AcCode').val().trim();
    //===========================check whether code exist already or not
    if (subA.length === 10) {
        str1 = "select AcCode from Account where AcCode='";
        str2 = str1 + subA + "'";
        GetCodeData(str2); //check whether code exist or not
        strRes = strRes.substring(1, strRes.length - 1);
        if (strRes.length > 0 && strRes != "") //if  code exist then return false and not allow to enter code   
        {
            alert('Code already exist cannot insert record');
            return false;
        }

    }
    //===============================
      if (subA.length === 2) {
        str1 = "select AcCode from Account where AcCode='";
        str2 = str1 + subA + "'";
        GetCodeData(str2); //check whether code exist or not
        strRes = strRes.substring(1, strRes.length - 1);
        if (strRes.length > 0 && strRes != "") //if  code exist then return false and not allow to enter code   
        {
            alert('Code already exist cannot insert record');
            return false;
        }

    }
    //============================
      if (subA.length === 4) {
        str1 = "select AcCode from Account where AcCode='";
        str2 = str1 + subA + "'";
        GetCodeData(str2); //check whether code exist or not
        strRes = strRes.substring(1, strRes.length - 1);
        if (strRes.length > 0 && strRes != "") //if  code exist then return false and not allow to enter code   
        {
            alert('Code already exist cannot insert record');
            return false;
        }

    }
    //=====================================end of code existence checking


    if (subA.length === 10) {//if user enter complete code
        sub4 = subA.slice(0, 4); //take first 4 digits of account code to check "0000"
        if (sub4 === '0000') {
            alert('Complete Code cannot Start with 0000');
            return false;
        } //end of chek first 4 digits are 0 or not
        //===================================================
        sub2 = subA.slice(0, 2); //get first 2 digits of account code
        // alert(sub2);
        str1 = "select AcCode from Account where AcCode='";
        str2 = str1 + sub2 + "'";
        GetCodeData(str2); //check whether 2 digits code exist or not
        //       alert(strRes);
        strRes = strRes.substring(1, strRes.length - 1);
        if (strRes.length > 0 && strRes != "") //if 2 digit code exist then chk for 4 digit code otherwise give message to create 2 digit code
        {
            var result;
            strRes = null;
            str2 = null;
            sub4 = subA.slice(0, 4); //get first 4 digits of account code
            str2 = str1 + sub4 + "'";
            result = Chk4DigitCode(str2)
            if (!result) {
                return false;
            }


            //                GetCodeData(str2); //check whether 4 digits code exist or not
            //                strRes = strRes.substring(1, strRes.length - 1);
            //                alert(strRes);
            //                if (strRes.length < 0) {
            //                    alert("First Create Sub Code of First Four Digits");
            //                    // alert("First Create Sub Code of First Four Digits");
            //                    //display message for create 4 digit sub code
            //                    //alert("");
            //                    //return false;

            //                }
        }
        else
            alert("First Create Control Code of Two Digits"); //display message for create 2 digit sub code
        return false;
    } //end of check length of code is 10
    //=================================
    else if (subA.length === 4) { //check whether user enter sub code
        sub2 = null;
        sub2 = subA.slice(0, 2);
        if (sub2 === '00') {
            alert('Sub Code cannot Start with 00');
            return false;
        } //end of chek first 2 digits are 0 or not
        //===========================
        sub2 = null;
        str1 = null;
        str2 = null;
        strRes = null;
        sub2 = subA.slice(0, 2); //get first 2 digits of sub code
        // alert(sub2);
        str1 = "select AcCode from Account where AcCode='";
        str2 = str1 + sub2 + "'";
        //strRes = GetCodeData(str2);
        //strRes = GetCodeData(str2); //check whether 2 digits code exist or not
        GetCodeData(str2); //check whether 2 digits code exist or not
        //       alert(strRes);
        strRes = strRes.substring(1, strRes.length - 1);
        if (strRes.length === 0 || strRes == "") {

            alert("First Create Sub Code of Two Digits");
            return false;

        }
    } //end of sub code checking
    return true;
}

这些javascript函数在firefor(firebug)中调试期间显示警报,但没有任何断点,表单上不显示警报,用户不知道点击保存按钮后发生了什么。

任何人都可以帮我解决这个问题

4

1 回答 1

1

可能你有一个提交的表单,然后页面会刷新,所以你不会得到你的 ajax 请求的结果。尝试处理“提交”事件而不是“点击”,阻止表单提交(您可以使用preventDefault,或者最后返回false),并自行处理

$('#form_id').submit(function (e) {
e.preventDefault();    
var isValid = validateForm();
if (isValid) {

    //***********************CODE TO SAVE DATA IN DATABASE***********************************
    var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
    $.ajax({
        url: '/Home/Save?action=Sve',
        type: "POST",
        data: JSON.stringify(person),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            //   $('#message').html('Record saved successfully' + result).fadeIn();
            alert("Record saved successfully");
        },
        error: function () {
            //    $('#message').html('Error Occurred').fadeIn(); 
            alert("Record not saved successfully");
        }
    });
}
else
    alert("form is not valid");

return false;

});  //end button clcik function
于 2013-04-22T09:10:46.950 回答