Autocomplete Web Service in ASP.Net web forms - asp.net

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.

Related

Script not works (ASP.NET MVC)

I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}

Unknown web method in asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}
You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});
Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

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.

making ajax call (in jquery) for webservice in 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

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources