How to call codebehind method from Jquery after autocomplete selection - c#

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that

You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});

Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});

You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}

Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.

This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

Related

Always error funtion is executing in json ajax in asp.net controller

Java Script:-
function themechange(themeValue) {
$('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
In LoginContoller.cs:-
[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.
You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST.
Try this
function themechange(themeValue) {
var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}

Autocomplete with Ajax returns No HTTP resource was found that matches the request URI

I am trying to implement an autocomplete on my textbox with data that comes from a web method. The webmethod works on the browser like:
http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e
and these are the results:
[{"IssuerID":1,"Name":"test tester","ChequeAccountNumber":"12345678","CurrencyCode":"EUR"}]
Now, I am trying to add on the textbox the Name data from the response but I'm getting an error in the function below:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?{ 'SearchString': 'e'}'.","MessageDetail":"No action was found on the controller 'ModuleTask' that matches the request."}
Below, my AJAX call seems to fail for a reason, which I believe comes from passing wrongly the parameters. I do not have experience with ajax so far, so your input will be great.
<script type="text/javascript">
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>',
data: "{ 'SearchString': '" + request.term + "'}",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
</script>
My web method:
public class ModuleTaskController : DnnApiController
{
[AllowAnonymous()]
[HttpGet()]
public HttpResponseMessage GetIssuers(string SearchString)
{
try {
List<Issuers> listIssuers = new List<Issuers>();
IssuersController ic = new IssuersController();
listIssuers = ic.GetIssuers(10, SearchString);
return Request.CreateResponse(HttpStatusCode.OK, listIssuers.ToJson);
} catch (Exception exc) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}
}
Any ideas?
EDIT:
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
var qstring = '?' + jQuery.param({ 'SearchString': request.term });
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
Your web method is a GET and accepts a querystring yet your Ajax call is trying to pass a JSON object, which is getting appended to the end of your url. You can see this by reading what the URL actually is, in the error message
There are a bunch of different things you can do. This is just one.
// turn your search object into querystring
var qstring = '?'+ jQuery.param({ 'SearchString': request.term});
// append this querystring to the end of your url
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring ,
// remove data and datatype
type: "GET",
//... etc
Also in this case, it doesn't look like you need the ResolveUrl.
Perhaps try your URL as:
url:'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers' + qstring;

jquery webmethod call returns whole page html

I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

jQuery Multiple Autocomplete with c#

I'm implementing multiple autocomplete using jQuery UI. Also I'm using webservice to pass values. I check jQuery UI demo for multiple autocomplete and using exact same code and it's working until the first autocomplete and adds a "," at the end.
But here I'm stuck, It's not searching for the next autocomplete. Well I didn't add a part of the code from the demo, which I don't know where it suppose to go. If someone could help me please.
Heare isthe My code
<script type="text/javascript">
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".tb")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//term: extractLast(request.term),
response($.map(data.d, function (item) {
return {
value: item.Email
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
search: function () {
// custom minLength
var term = extractLast(this.value);
alert(term);
if (term.length < 2) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
alert(terms);
// 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;
} //,
//minLength: 2
});
});
</script>
Here is the code I'm missing from jQuery UI demo
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
I don't know where to add this code:
term: extractLast( request.term )
here is the link for entire code Demo Code link
replace
data: "{ 'mail': '" + request.term + "' }"
with
data: "{ 'mail': '" + extractLast(request.term) + "' }"
this should work but i didn't like much the way you encode JSON, may create problems with quotes etc.

Categories

Resources