making ajax call (in jquery) for webservice in asp.net - asp.net

I want to validate product code for duplication using ajax call(in jquery) for webservice in which web method is written. now if success function executes as 'duplicate product code' it should not allow the user to save record. so how can i check this on Save buttons click event

First, create the below method in the page code behind.
using System.Web.Services;
[WebMethod]
public static bool CheckDuplicateCode(string productCode)
{
bool isDuplicate = false;
int pCode = Convert.ToInt32(productCode);
//check pCode with database
List<int> productCodes = GetProductCodeInDb();
foreach (var code in productCodes)
{
if (pCode == code)
{
isDuplicate = true;
break;
}
}
return isDuplicate;
}
And in the page markup just before the end body tag insert this code
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnSave.ClientID %>').click(function () {
SaveProduct();
});
});
function SaveProduct() {
//Get all the data that you are trying to save
var pCode = $('#<%= txtProductCode.ClientID %>').val();
//pass the product code to web method to check for any duplicate
$.ajax({
type: "POST",
url: "/InsertProductPage.aspx/CheckDuplicateCode",
data: "{'productCode': '" + pCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSuccees(msg);
},
error: AjaxFailed
});
}
function AjaxSuccees(msg) {
if (msg.d == true) {
return true;
//insert the rest of data
}
else {
alert("Product code already exists");
return false;
}
}
function AjaxFailed(msg) {
alert(result.status + ' ' + result.statusText);
}
</script>
Hope this helps

Related

Autocomplete Web Service in ASP.Net web forms

I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.
The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.
The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.
Code-Behind
public void getadd()
{
string address = "";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
TextBoxPicAddress.Text = address;
}
}
JavaScript
<script type="text/javascript">
function submit() {
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx.cs/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Markup
<asp:TextBox ID="TextBoxPicPostCode" runat="server"
CssClass="time"
onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server"
CssClass="address">
</asp:TextBox>
Make these changes
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
// change the function name from 'submit' here and at markup
function FetchAddress() {
//passing postalCode as string.
//Make sure that 'postalCode' is the parameter name at the webmethod
var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
//would be worthwhile to read about JSON.stringify, its the standard method
//var dataValue = JSON.stringify({ postalCode: $(".time").val() });
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd", // .cs is not required
data: dataValue,
contentType: 'application/json', //charset is not required
//dataType: 'json', // not required
success: function (result) {
var data = result.hasOwnProperty("d") ? result.d : result;
//alert("We returned: " + result.d);
// now we are assigning the return value to TextBoxPicAddress
$(".address").val(data);
}
});
}
</script>
Code-behind
//1. webmethod attribute required
[System.Web.Services.WebMethod]
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
string address = "No Address found!";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
+ postalCode + "&sensor=false";
xDoc.Load(remoteXml);
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
}
return address;
}
At markup, change the event as onblur="FetchAddress();"
P.S: No time to type all the changes made in detail, so added as comment
.cs is Not Required
and
public void getadd()
Should be Static
so
[System.Web.Services.WebMethod]
public static void getadd()
JScript
<script type="text/javascript">
function submit()
{
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
EDIT:
You Can't Use Controls Inside Static method. You nee to Refer This:
Using Jquery Ajax Call
Using AutoCompleteExtender
HTML
Javascript
`
function danish() {
var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();
$.ajax({
type: "POST",
url: "GoogleAPI.aspx/getadd",
contentType: 'application/json; charset=utf-8',
data: '{code: "' + code + '"}',
dataType: 'json',
success: function (result) {
$("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
}
});
return false;
}
</script>`
Codebehind
using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
[WebMethod]
public static List<string> getadd(string code)
{
string address = "";
List<string> lst = new List<string>();
XmlDocument xDoc = new XmlDocument();
var jsonSerialiser = new JavaScriptSerializer();
try
{
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
xDoc.Load(#"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
for (int i = 0; i < distanceX.Count; i++)
{
lst.Add(distanceX[i].InnerXml);
address = address + distanceX[i].InnerXml;
}
}
}
catch (Exception ex)
{
throw ex;
}
return lst;
}

Calling asp.net server function using jquery ajax

Am basically new to jquery. I have a function in aspx code bihind. I need to call it in a button click from aspx page using jquery. The server side function takes no arguement and returns no data.
The function the code behind is :
[WebMethod]
public void BindTreeview()
{
TreeView1.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(#"C:\ClientDocuments\Ford Retail Ltd\");
// output the directory into a node
TreeNode RootNode = OutputDirectory(RootDir, null);
// add the output to the tree
TreeView1.Nodes.Add(RootNode);
//TreeView1.SelectedValue = hdnSelectedNode.Value;
if (hdnSelectedNode.Value != string.Empty)
{
TreeView1.CollapseAll();
TreeNode searchNode = TreeView1.FindNode("Electricity");
if (searchNode != null)
searchNode.Expand();
}
}
aspx jquery is
$(document).ready(function () {
$('#btnNewFolder').click(function () {
// alert('Clicked');
$.ajax({
url: 'Default.aspx/BindTreeview',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert(1);
},
error: function (result) {
alert("The call to the server side failed. " + result.responseText);
}
});
});
});
When i run appln am getting alert on result.responseText. Where am i getting wrong? Quick response will be highly appreciable.
mark your method as static
public static void BindTreeview()

ASP.NET Validate membership email from ClientSideEvents and WebMethod

I have ASPxGridview and i want to check if email already registered before or not in editform using ClientSideEvents.
Any help to resolve this problem ?
aspx section
this is the javascript section
function OnEmailValidation(s, e) {
var error = "";
var tfld = trim(e.value);
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!illegalChars.test(tfld)) {
$get("spanEmail").innerHTML = "invalid email";
} else {
PageMethods.CheckEmail(e.value.toString(), OnCheckEmail);
// how to check OnCheckEmail before continue
//if(email already registered) {
// return false
//}
$get("spanEmail").innerHTML = "";
}
return true;
}
function OnCheckEmail(unavailable) {
if (unavailable == true) {
$get("spanEmail").innerHTML = "already registered";
$get("spanEmail").style.color = "red";
}
else if (unavailable != true) {
$get("spanEmail").innerHTML = "Available";
$get("spanEmail").style.color = "#76EB69";
}
}
aspx.cs
col_Email.PropertiesTextEdit.ClientSideEvents.Validation = "OnEmailValidation";
grid.Columns.Add(col_Email);
[WebMethod]
public static bool CheckEmail(string email)
{
System.Threading.Thread.Sleep(200);
if (Membership.FindUsersByEmail(email) != null)
{
if (Membership.FindUsersByEmail(email).Count <= 0)
{
return false;
}
return true;
}
else
{
return false;
}
}
This is my final code after the
Filip
advice but i have mini problem:
When i use
(async: false) and cntr.SetIsValid(false);
the control doesn't apply the action
but If i use
(async: true) and cntr.SetIsValid(false);
the control apply the action
Why ?
I want to use async: false
function OnEmailValidation(s, e) {
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var spanEmail = document.getElementById("spanEmail");
var obj = GetObj('txt_Email');
var cntr = aspxGetControlCollection().Get(obj.id);
if (!illegalChars.test(e.value)) {
spanEmail.innerHTML = "Invalid Email";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
} else {
$.ajax({
type: "POST",
async: false,
url: "myweb_service.asmx/CheckEmail",
data: "{'email':'" + e.value.toString() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d == "true") {
spanEmail.innerHTML = "Email register before";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
}
if (res.d == "false") {
spanEmail.innerHTML = "Available";
spanEmail.style.color = "#76EB69";
cntr.SetIsValid(true);
}
}
});
}}
You can use jQuery to call PageMethods (replace PageMethods.CheckEmail call with this code):
$.ajax({
type: "POST",
async: false,
url: "<PageName>.aspx/CheckEmail",
data: "{" + e.value.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d)
return false;
}
});
Replace PageName with your page name.
Be careful with synchronous (async: false) ajax calls. They will block your page until request finishes.
If res.d doesn't return result or you just want detailed explanation of posted code check these links:
Using jQuery to directly call aspnet ajax page methods
A breaking change between versions of aspnet ajax
You will need to set up a web service on the server side that will check if the email already exists. Then you will use JavaScript AJAX (preferably a library like jQuery or Prototype) to query the web service during your validation method.
it will be a good deal of work to get it all set up. Good luck. See one of these links for more information:
http://msdn.microsoft.com/en-us/library/bb532367.aspx
http://msdn.microsoft.com/en-us/library/t745kdsh.aspx

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

Resources