简体   繁体   English

asp.net/JavaScript ClientSide CustomValidation WebMethod

[英]asp.net / JavaScript ClientSide CustomValidation WebMethod

I'm trying to do Client-Side validation via a javascript function. 我正在尝试通过javascript函数进行客户端验证。 I have an ASP.NET c# page, that successfully calls a WebMethod (from pages code behind) to validate data entered is accessible to the user. 我有一个ASP.NET c#页面,该页面成功调用了WebMethod(从后面的页面代码)来验证输入的数据是否可供用户访问。 I have a textbox with AJAX AutoCompleteExtender and this works fine. 我有一个带有AJAX AutoCompleteExtender的文本框,可以正常工作。 I have CustomValidator that I'm trying to call a javascript function to validate the data. 我有CustomValidator,正在尝试调用javascript函数来验证数据。 The webmethod (which pulls from SQL database) is executing and returning data as expected. Web方法(从SQL数据库提取)正在按预期方式执行并返回数据。 The Javascript is executing the webmethod. Javascript正在执行网络方法。 The issue is the PageMethods is using an 'OnSuccess' function (a nested function from the javascript function being called) however from the OnScuess function I can't set the args.IsValid = true/false. 问题是PageMethods使用的是'OnSuccess'函数(来自javascript函数的嵌套函数),但是从OnScuess函数中,我无法设置args.IsValid = true / false。 I can set this property in the original function but in order to do that I need both the args.Value and result from the OnSuccess in order to evaluate if it is valid. 我可以在原始函数中设置此属性,但要做到这一点,我需要args.Value和OnSuccess的结果来评估它是否有效。 Both are not accessible from each other. 两者不能互相访问。 I've tried hiddenfields to set the value to evaluate, I've tried 'Global' variables in JavaScript. 我尝试了hiddenfields来设置要评估的值,我尝试了JavaScript中的“全局”变量。 Nothing seems to give me the desired results. 似乎什么都没有给我想要的结果。 Both the hidden field as well as the 'Global' variable is not getting set before the evaluation to set the args.IsValid. 在设置args.IsValid的评估之前,未同时设置隐藏字段和'Global'变量。 Can someone please help. 有人可以帮忙吗? I can't believe how difficult such a simple task has become. 我不敢相信这样一个简单的任务变得多么困难。 The only way I'm getting the validation error message to show up is if I manually set the args.IsValid and issue an alert("doesn't mater what I put in here") at the bottom of the javascript primary function. 要显示验证错误消息的唯一方法是手动设置args.IsValid并在javascript主要函数的底部发出警报(“不符合我在此处输入的内容”)。 I don't want an alert, I just want a message displayed next to my text box. 我不需要警报,只希望在文本框旁边显示一条消息。 Eventually this will go into a gridview (will have input boxes on each item row to allow multiple row edits at once. 最终,这将进入gridview(每个项目行上都有输入框,以允许一次进行多行编辑。

I know a simple solution would be to have a dropdownlist but and serverside validation as well however this is not what I need. 我知道一个简单的解决方案是拥有一个下拉列表,但是还有服务器端验证,但这不是我所需要的。

Here is my javascript function 这是我的JavaScript函数

function pmValidateGLAccount(oSrc, args) {
    var GLIsValid;
    PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess);
    function OnSuccess(result) {
        // I NEED TO DETERMINE IF IS VALID BUT SET THE args.IsValid after the process leaves this nested function
        if (args.Value != result) {
            GLIsValid = false;
        }
        else {
            GLIsValid = true;
        };
    };// THIS IS THE END OF THE ONSUCCESS FUNCTION
    //args.IsValid = false; //THIS IS WHERE WE NEED TO SET THE IsValid

} // THIS IS THE END OF THE pmValidateGLAccount FUNCTION

here is my CustomValidator 这是我的CustomValidator

<asp:CustomValidator ID="CustomValidator1" 
runat="server" 
ControlToValidate="TextBox1"  
ValidationGroup="vg_test" 
ClientValidationFunction="pmValidateGLAccount" 
ErrorMessage="Error: Please Enter an Account Number from the list" 
Display="Dynamic"></asp:CustomValidator>

here is my webmethod 这是我的网络方法

[System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()]
public static string ValidateGLAccountAccess(string GLAccountNum)
{

    string RetValue = string.Empty;
    string CurUser = HttpContext.Current.User.Identity.Name.ToString();
    string CurUserRemoveDomain = string.Empty;
    int i = CurUser.IndexOf("\\");
    if (i != -1)
    {
        CurUserRemoveDomain = CurUser.ToLower().Replace(Resources.AppSettings.ActiveDirectoryDomain.ToString().ToLower() + "\\", "");
        CurUser = CurUserRemoveDomain;
    }

    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["CustDBConn"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand("MySproc", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@SearchString", GLAccountNum);
            cmd.Parameters.AddWithValue("@UserName", CurUser);
            cmd.Connection = conn;
            conn.Open();
            RetValue = (string)cmd.ExecuteScalar();
            conn.Close();
        }
    }
    return RetValue;
}

Ok so for those that are still fighting with a means of a synchronous client-side validation solution. 好吧,对于仍在使用同步客户端验证解决方案的解决方案的人。 I finally got the solution working. 我终于找到了解决方案。 I was reluctant to experiment with jQuery, but wish I would have days ago. 我不愿尝试使用jQuery,但希望我能在几天前​​完成。

What I was trying to accomplish was a textbox autocomplete that would pass the username to the database and begin returning data specific for that user. 我试图完成的是一个文本框自动完成功能,该功能会将用户名传递给数据库,并开始返回特定于该用户的数据。 Then to prevent any input in the textbox other than from the permitted autocomplete list, I used the CustomValidator with jQuery. 然后,为了防止在文本框中输入任何内容(除了允许的自动完成列表以外),我将CustomValidator与jQuery一起使用。 What this did is take the final input string along with the username and passed it to the database. 这是将最终输入字符串和用户名一起使用,并将其传递给数据库。 If the database returned a record with the matching string, the selection was valid; 如果数据库返回带有匹配字符串的记录,则该选择有效;否则,该选择有效。 if not, the selection is marked as invalid. 如果不是,则将该选择标记为无效。

I fought for so long with this, I wanted to give others an 'as complete as possible' guide. 我为此花了很长时间,我想给别人一个“尽可能完整”的指南。 For those that have not used jQuery, neither had I prior to this and that portion took the least amount of time to come up with this solution. 对于那些没有使用jQuery的人,我之前也没有使用过,而那部分花费最少的时间来提出此解决方案。 I hope this helps someone out there. 我希望这可以帮助某个人。

Here is exactly what I did: 这正是我所做的:

  1. Downloaded the jQuery script and placed it in my scripts folder. 下载了jQuery脚本并将其放在我的脚本文件夹中。 Added a reference to the jQuery in my MasterPage.Master header section. 在我的MasterPage.Master标头部分中添加了对jQuery的引用。 Modified the ScriptManager (in the body) to EnablePageMethods. 将ScriptManager(在主体中)修改为EnablePageMethods。

     <script type="text/javascript" src="/scripts/jquery-1.4.2.js"></script> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager> 
  2. Added the JavaScript just inside my content place holder in TextBoxAutoFill.aspx. 在TextBoxAutoFill.aspx的内容占位符中添加了JavaScript。

     <script type="text/javascript"> function pmValidateGLAccount(oSrc, args) { $.ajax({ type: "POST", async: false, url: "TextBoxAutoFill.aspx/ValidateGLAccountAccess", data: "{ GLAccountNum: " + "'" + args.Value + "' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { args.IsValid = response.d; } }); }; </script> 
  3. Created my TextBox, AutoCompleteExtender and CustomValidator 创建了我的TextBox,AutoCompleteExtender和CustomValidator

     <asp:TextBox TabIndex="1" autocomplete="off" ID="TextBox1" runat="server" Width="250px" ValidationGroup="vg_test"></asp:TextBox> <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" EnableCaching="true" CompletionSetCount="10" ShowOnlycurrentWordInCompletionListItem="true" CompletionInterval="500" CompletionListCssClass="AJAXAutosuggestTextBox" DelimiterCharacters="" Enabled="True" ServiceMethod="GetAccountNumbers" TargetControlID="TextBox1" MinimumPrefixLength="4" > </asp:AutoCompleteExtender> <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1" ValidationGroup="vg_test" ClientValidationFunction="pmValidateGLAccount" ErrorMessage="Error: Please enter an account number from the list" Display="Dynamic"></asp:CustomValidator> 
  4. Added the WebMethod for my AutoCompleteExtender (This is in the TestBoxAutoFill.aspx.cs file) 为我的AutoCompleteExtender添加了WebMethod(位于TestBoxAutoFill.aspx.cs文件中)

     [System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()] public static List<string> GetAccountNumbers(string prefixText, int count) { string CurUser = HttpContext.Current.User.Identity.Name.ToString(); string CurUserRemoveDomain = string.Empty; int i = CurUser.IndexOf("\\\\"); if (i != -1) { CurUserRemoveDomain = CurUser.ToLower().Replace(Resources.AppSettings.ActiveDirectoryDomain.ToString().ToLower() + "\\\\", ""); CurUser = CurUserRemoveDomain; } using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager.ConnectionStrings["CustDBConn"].ConnectionString; using (SqlCommand cmd = new SqlCommand("SP_PCard_Get_AutoCompleteAccountNumbers", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@RecCount", count); cmd.Parameters.AddWithValue("@SearchString", prefixText); cmd.Parameters.AddWithValue("@UserName", CurUser); cmd.Connection = conn; conn.Open(); List<string> AccountNumbers = new List<string>(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { AccountNumbers.Add(sdr["ACTNUMST"].ToString()); } } conn.Close(); return AccountNumbers; } } } 
  5. Added the WebMethod for validation (This is in the TestBoxAutoFill.aspx.cs file) 添加了用于验证的WebMethod(位于TestBoxAutoFill.aspx.cs文件中)

     [System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethod()] public static bool ValidateGLAccountAccess(string GLAccountNum) { string RetValue = string.Empty; string CurUser = HttpContext.Current.User.Identity.Name.ToString(); string CurUserRemoveDomain = string.Empty; int i = CurUser.IndexOf("\\\\"); if (i != -1) { CurUserRemoveDomain = CurUser.ToLower().Replace(Resources.AppSettings.ActiveDirectoryDomain.ToString().ToLower() + "\\\\", ""); CurUser = CurUserRemoveDomain; } using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager.ConnectionStrings["CustDBConn"].ConnectionString; using (SqlCommand cmd = new SqlCommand("SP_PCard_Get_SelectedGLAcountNumber", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SearchString", GLAccountNum); cmd.Parameters.AddWithValue("@UserName", CurUser); cmd.Connection = conn; conn.Open(); RetValue = (string)cmd.ExecuteScalar(); conn.Close(); } } Boolean myVarBool = false; if (RetValue == GLAccountNum) { myVarBool = true; } return myVarBool; } 

Hmm I didn't play much with .NET C# but usually i just using JQuery validation and AJAX for web apps. 嗯,我对.NET C#的使用并不多,但是通常我只对Web应用程序使用JQuery验证和AJAX。

I try to answer your question, i can't try..but might be will little bit help : 我尝试回答您的问题,我无法尝试..但可能会有所帮助:

  1. please make sure the PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess); 请确保PageMethods.ValidateGLAccountAccess(args.Value,OnSuccess); return right result? 返回正确的结果?

  2. Try this and debug it with alert(args.IsValid) after you try this code : 尝试以下代码后,尝试使用alert(args.IsValid)对其进行调试:

     function pmValidateGLAccount(oSrc, args) { var GLIsValid; args.IsValid =false; PageMethods.ValidateGLAccountAccess(args.Value, OnSuccess); function OnSuccess(result) { if (args.Value != result) { GLIsValid = false; // or you don't need this args.IsValid= false; alert(args.IsValid); } else { GLIsValid = false; // or you don't need this args.IsValid= true; alert(args.IsValid); } } 

    } }

  3. Sorry if that not your mean, but if you need to get it..you can put the "var GLIsValid;" 抱歉,这不是您的意思,但是如果您需要得到它,您可以输入“ var GLIsValid;”。 outside the function as global variable..if you defined on that function it's mean just can be access on that function wrap. 在函数外部作为全局变量..如果您在该函数上定义,则意味着可以对该函数包装进行访问。 THank you 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM