ValidateUserName is undefined - c#

I have a jquery ajax call asp.net web service question. I want to validate a textbox in asp.net web page.
The validator is:
<asp:CustomValidator ID="CustomValidatorUser" runat="server" ControlToValidate="TextUserName"
ErrorMessage="Minimum of 6 (six) alphanumeric characters."
ClientValidationFunction="ValidateUserName" Display="Dynamic"
ValidateEmptyText="True" ></asp:CustomValidator>
The jquery code is(updated 2nd):
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script src="../jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': " + $("#TextUserName").val() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
</script>
<div>
General user information</div>
<p>
</p>
<table cellpadding="2">
The web service code is:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UserNameWebService : System.Web.Services.WebService
{
[WebMethod]
public bool ValidateUserName(string strUsername)
{
string UserNameCreated = strUsername;
string AD_Server = System.Configuration.ConfigurationManager.AppSettings["AD_Server"];
DirectoryEntry entry = new DirectoryEntry(AD_Server);
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(objectClass=user)(samaccountname=" + UserNameCreated + "))";
SearchResultCollection results = deSearch.FindAll();
Match match = Regex.Match(UserNameCreated, #"^[a-zA-Z0-9]{6,}$", RegexOptions.IgnoreCase);
if (results.Count > 0)
return false;
else if (match.Success)
return true;
else
return false;
} }
But I got an error:
ValidateUserName is undefined.
Please help me to correct the error.
Thank you very much!

There are actually several problems with your code.
1) $("#TextUserName") will not work in this context because asp.net will render the server-side TextBox control with a different ID. You would need to do this instead:
data: "{'strUsername': " + $("#<%=TextUserName.ClientID%>").val() + "}",
2) The json in your data attribute is not formatted correctly, you need single quotes ' around the value like this:
| |
V V
data: "{'strUsername': '" + $("#<%=TextUserName.ClientID%>").val() + "'}",
3) You need to put your Jquery ajax call inside a function, which in your case is called ValidateUserName. It takes two parameters source and args. The responsibility of this function is to set the value of args.IsValid to either true or false. So you will need to provide a function to be called when the ajax call succeeds that can perform this logic. Like this:
function ValidateUserName(source, args) {
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
args.IsValid = result.d;
}
});
}
4) As you can see in the code above, you don't actually need to use jquery to get the value from the textbox because you can access it like this args.Value.
5) You need to add async: false otherwise by the time IsValid is set, the code that sets the visibility of the message will already have been executed, and so nothing will happen.

You need to encase your ajax function in a function call ValidateUserName so it matches ClientValidationFunction.
function ValidateUserName(){
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': " + $("#TextUserName").val() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Even then, this isn't returning a value. I think you'll need to use the success option of the $.ajax function to set a boolean value to return to the function.
So you would do something like:
function ValidateUserName(){
var isValid;
$.ajax({
type: "POST",
url: "UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" + $("#TextUserName").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
, async: false
, success: function(data){
isValid = data;
}
});
return isValid;
}
Notice I've also set async to false.

Related

webmethod isn't catching ajax POST

I'm trying to call a server side method with ajax. This is what I've got:
Client side:
function accept(thisButton) {
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: '{param: "' + $(thisButton).prev().val() + '" }',
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}
Server side:
[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
return maxUsers; //I also have a breakpoint here that isn't stopping the execute
}
When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?
EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.
The parameters of your WebMethod need to match the parameter name you are passing in.
Change
data: '{param: "' + $(thisButton).prev().val() + '" }',
to
data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',
1.Go to App_Start/RouteConfig and change
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
2.As #F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:
function accept(thisButton) {
var data = {};
data.maxUsers = $(thisButton).prev().val();
$.ajax({
type: "POST",
url: "Default.aspx/editMaxUsers",
data: JSON.stringify(data),
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (result) { alert("successful" + result.d); }
});
}

JQuery AJAX method executes both "success" and "failure"

I have an AJAX method to tell the user whether or not an email is available when registering.
$('#mainArea_txtEmail').keyup(function (e) {
var inputemail = $(this).val();
if (inputemail.length > 5)
{
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert("available"),
failure: alert("unavailable")
});
}
});
When a user types in an email, whether it is available or not, the browser displays the success alert and then the failure alert every time.
Here is the C# method:
[System.Web.Services.WebMethod]
public static string isEmailAvailable(string email)
{
BasePage page = new BasePage();
string returnvalue;
if (page.db.UserGet(email) == null)
{
returnvalue = "true";
}
else
{
returnvalue = "false";
}
return returnvalue;
}
The db.UserGet method will try and find a database record of a user with the email address matching the email parameter. If there is one, then a User class instance is populated and page.db.UserGet is not null, meaning the email is taken. If it is still null, then no user with that email was found and the email is available.
What am I doing wrong here?
I was following this tutorial (http://www.c-sharpcorner.com/UploadFile/20abe2/how-to-check-user-name-or-email-availability-using-Asp-Net)
Your syntax won't work, you can't use alert as the callback function. alert needs to be wrapped in a proper function or it will fire immediately
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(serverResponse) {
alert("available");
/* do something with serverResponse */
},
failure: function() { alert("available"); }
});
$.ajax API Reference

Get ASP Page Method return from jQuery

I have an aspx page. I want to call the ASP.NET method via jquery. I have implemented the code but the problem is that I am getting the HTML of whole page rather than getting the returned string from ASP method. I need some assistance.
Here is my code:
[WebMethod]
public string PopulateData(string coursename)
{
return "called";
}
and here is the jquery method:
var subject = 'database';
$.ajax({
type: "POST",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
Add in the contentType and dataType.
var subject = 'database';
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "CourseDetail.aspx/PopulateData",
data: "{coursename:'" + subject + "'}",
success: function (msg) {
// Do something interesting here.
alert('result : ' + msg);
}
contentType is the header sent to the server, specifying a particular format.
Example: I'm sending json or XML
dataType is telling jQuery what kind of response to expect.
Expecting JSON, or XML, or HTML, etc....

Call code behind method in jquery, not finding the method

My code behind:
[WebMethod]
public bool accountExists(string username, string password) {
//code...
}
My jquery:
$.ajax({
type: "POST",
url: "MyPage.ascx/accountExists",
data: JSON.stringify({ username: txtUsername.val(), password: txtPassword.val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d)
},
error: function(msg) {
alert("ERROR: " + msg.d)
}
});
I always reach the alert where it says "ERROR: " + msg.d.
MyPage.ascx is located in a folder "Controls", so I have tried to set the url: "Controls/MyPage.ascx/accountExists" without any change.
ASP.NET AJAX Page Methods are intended to run inside of .aspx pages and not .ascx user controls.
Move your WebMethod logic into an .aspx page and update the AJAX call via jQuery.

Redirect after an ajax request in a click event

I'm using JScript + ASP.NET. I got a form with 2 inputs (user and password) and a button. What I'm trying to do is to:
1- Fire a click event
2- Look inside a database if the user exist
3- Give back the answer
4- If the answer is true, POST some data to an other page AND redirect to it.
I first tried to do this with ASP.NET. To POST data with ASP.NET I need to use PostBackUrl property, but the problem is that PostBackUrl ignore my click event.
I then tried to do this with jscript. On my click event (jquery), I use $.ajax to POST data to access my database, give the answer back in json...and I'm stuck there. In both method, I'm stuck at point 4.
ASP.NET
protected void SignIn_OnClick(object sender, EventArgs e)
{
Clients client = (Clients)clientDAO.getUsername(text1.Text, password2.Text);
if (client != null)
{
Session.Add("SessionNoClient", "1272");
Session.Add("CurrentQuote", "-1");
Session.Add("UnitSystem", "0");
Session.Add("SessionAdministrator", "0");
//How to redirect with POST here
}
}
JScript:
$("#m_bLogin").click(function () {
var username = $("#text1").val();
var password = $("#password2").val();
var form = $("#formClient");
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
});
});
You could do something like that:
$.ajax({
url: '../../Class/LoginAjax.asmx/GetLoginInformation',
data: "{ 'Name':'" + username + "','Password':'" + $("#password2").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//My Json returns {"'Name':'Bob','Password':'1234'} and I'm not able to access Name or Password property. I tried data.d, data.d.Name, eval(data.d.Name) etc...
form.submit();
},
error: function (XMLHttpRequest, textStatus, error) {
alert(error);
}
}).done(function() {
window.location.href = "YourNewPage.aspx";
});

Categories

Resources