mvc3中未显示javascript警报消息

时间:2013-04-22 07:49:27

标签: javascript asp.net-mvc-3 jquery

我正在研究mvc3和wcf服务中的会计项目。我正在使用javascript,ajax进行表单验证。我在javascript中编写验证表单的代码。但是我的javascript警报没有显示给用户。尽管我在brwoser中启用了javascript。当我调试代码然后javascript lerts显示但没有调试代码如果表单提交然后警报消息验证不会显示给我。

下面的

是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)调试期间显示警告但没有任何断点,表单上没有显示警报,用户dnt知道保存按钮点击后发生了什么。

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

1 个答案:

答案 0 :(得分: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
相关问题