c# - asp.net call asynchronous webMethod with Jquery -
i'm trying create asp application, can write departure , destination city. implement google autocomplete on textbox.
i've developed async method homecoming autocomplete function of google when insert letter or more called 'getautocomplete'.
now want access javascript, ajax request.
here code aspx
<%@ page async="true" title="home page" language="c#" masterpagefile="~/site.master" autoeventwireup="true" codebehind="default.aspx.cs" inherits="googleapiweb._default" %> <asp:content runat="server" id="bodycontent" contentplaceholderid="maincontent"> <ol class="round"> <div id="departure_city" style="margin-top: 15px; margin-left: 15px;"> <asp:label id="lbldeparturecity" runat="server" text="ville de départ"></asp:label> <asp:textbox runat="server" id="txbdeparturecity" clientidmode="static" style="width: 150px;"></asp:textbox> </div> <div id="destination_city" style="margin-top: 15px; margin-left: 15px;"> <asp:label id="lbldestinationcity" runat="server" text="ville d'arrivé"></asp:label> <asp:textbox runat="server" id="txbdestinationcity" clientidmode="static" style="width: 150px;"></asp:textbox> </div> <asp:button id="buttonvalider" runat="server" text="valider" clientidmode="static" onclick="buttonvalider_click" /> <asp:label id="lbl1" runat="server" text=""></asp:label> <asp:label id="lbl2" runat="server" text=""></asp:label> </ol> <script type="text/javascript"> $(document).ready(function () { //autocomplete $("#txbdeparturecity").bind("change paste keyup", function () { $.ajax({ type: "post", url: "/default.aspx/getautocomplete", data: "{'element':'" + $(this).val() + "'}", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (response) { alert(response.d); } }); }); $("#txbdestinationcity").bind("change paste keyup", function () { $.ajax({ type: "post", url: "/default/googleautocomplete", data: "{'element':'" + $(this).val() + "'}", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (response) { if (response.d == "nok") { //errorresponsealert(); } } }); }); }); </script>
now on code behind
namespace googleapiweb { public partial class _default : page { protected void page_load(object sender, eventargs e) { } #region webmethod autocomplete googleapi [webmethod(enablesession = true)] public static string googleautocomplete(string element) { string x = getautocomplete(element); homecoming ""; } [webmethod(enablesession = true)] private static async task<string> getautocomplete(string element) { // adresse à compléter string location = element; // message d'erreur s'il y en string error = ""; // créer une instance d'auto finish autocomplete autocomplete = new autocomplete(); // options de l'auto finish autocompleteoptions options = new autocompleteoptions() { // obtenir les résultats en français language = languageenum.french, // pays dans lequel vous souhaitez limiter vos résultats // attending : format iso 3166-1 : "us", "fr", "de", ... countryfilter = "fr", // type de résultats à retourner. // ex : regions retourne le code postal, ce que ne fait pas cities. // si cette alternative est vide, tous les résultats sont retournés. typefilter = typefilterenum.regions }; // clé api string key = "xxxxxxx"; // appel asynchrone de la méthode de la dll var listoflocation = await autocomplete.getautocomplete(location, key, null).continuewith(t => { // s'il y une erreur if (t.isfaulted) { // message de l'exception error = t.exception.innerexception.message; homecoming null; } // résultat homecoming t.result; }); var result = listoflocation.first(); homecoming result; } #endregion protected void buttonvalider_click(object sender, eventargs e) { gettrip(); getautocomplete(txbdeparturecity.text); } } }
and error post http://localhost:51460/default.aspx/getautocomplete 500 (internal server error)
how can manage this, in order on ajax success function result of method. aim of this, obtain result no callback.
thank you
ok, figured out how solve this. in order phone call in ajax web method, web method have homecoming string. method cannot async.
i added class on code behind
public static class asynchelpers { /// <summary> /// execute's async task<t> method has void homecoming value synchronously /// </summary> /// <param name="task">task<t> method execute</param> public static void runsync(func<task> task) { var oldcontext = synchronizationcontext.current; var synch = new exclusivesynchronizationcontext(); synchronizationcontext.setsynchronizationcontext(synch); synch.post(async _ => { seek { await task(); } grab (exception e) { synch.innerexception = e; throw; } { synch.endmessageloop(); } }, null); synch.beginmessageloop(); synchronizationcontext.setsynchronizationcontext(oldcontext); } /// <summary> /// execute's async task<t> method has t homecoming type synchronously /// </summary> /// <typeparam name="t">return type</typeparam> /// <param name="task">task<t> method execute</param> /// <returns></returns> public static t runsync<t>(func<task<t>> task) { var oldcontext = synchronizationcontext.current; var synch = new exclusivesynchronizationcontext(); synchronizationcontext.setsynchronizationcontext(synch); t ret = default(t); synch.post(async _ => { seek { ret = await task(); } grab (exception e) { synch.innerexception = e; throw; } { synch.endmessageloop(); } }, null); synch.beginmessageloop(); synchronizationcontext.setsynchronizationcontext(oldcontext); homecoming ret; } private class exclusivesynchronizationcontext : synchronizationcontext { private bool done; public exception innerexception { get; set; } readonly autoresetevent workitemswaiting = new autoresetevent(false); readonly queue<tuple<sendorpostcallback, object>> items = new queue<tuple<sendorpostcallback, object>>(); public override void send(sendorpostcallback d, object state) { throw new notsupportedexception("we cannot send our same thread"); } public override void post(sendorpostcallback d, object state) { lock (items) { items.enqueue(tuple.create(d, state)); } workitemswaiting.set(); } public void endmessageloop() { post(_ => done = true, null); } public void beginmessageloop() { while (!done) { tuple<sendorpostcallback, object> task = null; lock (items) { if (items.count > 0) { task = items.dequeue(); } } if (task != null) { task.item1(task.item2); if (innerexception != null) // method threw exeption { throw new aggregateexception("asynchelpers.run method threw exception.", innerexception); } } else { workitemswaiting.waitone(); } } } public override synchronizationcontext createcopy() { homecoming this; } }
and in webmethod
[webmethod(enablesession = true)] public static string googleautocomplete(string element) { string result = ""; list<string> lstreturngoogle = asynchelpers.runsync<list<string>>(() => getautocomplete(element)); if (lstreturngoogle != null) { result = "["; foreach (string t in lstreturngoogle) { result += '"' + t + '"' + ','; } result = result.remove(result.length - 1, 1); result += "]"; result.replace('\\', ' '); } homecoming result; }
with this, can phone call webmethod in ajax, , have right response.
c# javascript jquery asp.net ajax
No comments:
Post a Comment