javascript警报消息未在mvc3中显示 [英] javascript alert messages is not show in mvc3

查看:48
本文介绍了javascript警报消息未在mvc3中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on accounting project in mvc3 and wcf services. i am using javascript,ajax for form validation. i write the code for validate form in javascript. but my javascript alerts are not shown to user.although i enable javascript in brwoser. while i debug the code then javascript lerts was show but without debugging code if form is submit then alert messages for validation are not display to me.

下面是mvc3中表单的代码

below is the code of form in 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文件代码

below is my test.js file code

  $('#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知道单击保存按钮后发生了什么.

these function of javascript are displaying alerts during debugging in firefor (firebug) but without any breakpoint no alert is display on form and user dnt know what happened after save button click.

任何人都可以帮助我消除此问题

anyone help me to remove this problem

推荐答案

可能您有一个已提交的表单,此后页面刷新了,因此您不会得到ajax请求的结果.尝试处理提交"事件而不是单击"事件,阻止表单提交(您可以使用preventDefault或为此最后返回false),然后由您自己处理

Probably you have a form there which is submitted, and page gets refreshed after that, so you won't get result of your ajax request. Try handling "submit" event instead of a "click", prevent form submission (you can either use preventDefault, or return false in the end for this), and handle it by yourself

$('#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

这篇关于javascript警报消息未在mvc3中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆