Showing posts with label return. Show all posts
Showing posts with label return. Show all posts

Wednesday, March 28, 2012

Calling javascript from ASP.NET AJAX

I am trying to read a cookie with some javascript, without postback, using a timer control. I all need to do is return the value of the .js file and use it in the timer event.

So far here's what I have done:

I have a ScriptManager and an updatepanel with a timer control inside.

I set the ScriptReference to the file that reads the cookie:

<Scripts>
<asp:ScriptReference Name="ReadCookie" Path="javascripts/ReadCookie.js" />
</Scripts>

The timer calls this event:

protected void Timer1_Tick(object sender, EventArgs e)
{

}

My Question is how do I call that cookie and access the value in my code behind?

Thanks, Justin.

I guess I'll should restate my question:

How do I call a javascript function that has been added to the scripts collection of the scriptmanager (as shown above) from my c# codebehind?

Thanks, Justin.


You can register that JavaScript function in Timer's Tick Event.


Yes, I have tried that with no success but maybe I am doing it wrong:

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="ReadCookie.js"/>
</Scripts>
</asp:ScriptManagerProxy>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick="readCookie">
</asp:Timer>

....

readCookie.js:

function readCookie() {
var nameEQ = "PhoneNumber" + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}

if (c.indexOf(nameEQ) == 0){
return c.substring(nameEQ.length,c.length);
}
else {
return null;
}
}
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

I Get this Error:

Compiler Error Message:CS0117: 'ASP.agents_customerdetailsform_aspx' does not contain a definition for 'readCookie'


Hi, Justin


Check this link for answer and more help:

  • CS0117 :: 'Type' does not contain a definition for 'Identifier' :http://dotnetslackers.com/_NET/re-56753_CS0117_Type_does_not_contain_a_definition_for_Identifier.aspx

  • calling a VB class from Javascript?

    Hi, I created a webservice to return a dataset for my autocomplete word list. Now, I am wondering if it's possible that we could call a vb class in javascript function? Eg.

    HTML:<inputtype="text"onkeypress="return getList(this);"id="strSearch"/>

    Javascript: function getList(word) { // call or invoke vb class to return dataset }

    If that is impossible, is there anyway to create a autocomplete WITHOUT using XMLHTTP ..?

    Take a look at pagemethods with the script manager.


    I think you can use Async Postback. Take a look athttp://forums.asp.net/t/1168088.aspx

    Let me know if it answers your question.

    Thanks


    Unless you remote script it in an iframe, whatever you do with AJAX is going to use XmlHttpRequest. Why do you want to avoid that?

    Page methods might work well for what you're doing, though you'd need to convert your DataSet to an array before returning it. The AJAX framework doesn't support serializing DataSets to JSON quite yet (soon).

    However, if all you want is an auto completing TextBox, you should just take a look at theAutoComplete extender in the AJAX Toolkit. No point in re-inventing the wheel.


    No, JavaScript can not call a function that is serverside code. It can only call JavaScript code. If you want to call code on the server, you should ook into using the pagemethod,http://forums.asp.net/t/1175553.aspx:

    For more infomation, seehttp://www.asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx, especially the following section:

    Calling Static Methods in an ASP.NET Web Page

    You can add static page methods to an ASP.NET page and qualify them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods in a page, import theSystem.Web.Services namespace and add aWebMethodAttribute attribute to each static method that you want to expose.

    To be able to call static page methods as Web methods, you must set theEnablePageMethods attribute of theScriptManager control totrue.

    The following example shows how to call static page methods from the client script to write and read session-state values.

    RunView

    Best Regards,

    Calling a Page Method Instead of a Web service method with javascript?

    Hi All,

    I am just wondering if it is possible to call a page method or a static method (non webservice) with javascript and have it return the results to the calling javascript funciton just like how it is done with a webservice call? Personally I prefer not to be producing asmx's for things that may only be used on a single page.

    If so ... how might I accomplish this?

    If Not.... Why not?

    hehe

    Thanks

    Hi miskiw

    Yes you can do that, you can find details here

    http://ajax.asp.net/docs/tutorials/useWebServiceProxy.aspx at the bottom of the page titled "To call a static page method".

    It is worth noting that there is a bug with this in the current release where you can only call methods that are inline. You cannot currently make async calls to methods that are in code behind.

    HTH

    Andy.


    http://ajax.asp.net/docs/tutorials/useWebServiceProxy.aspx

    can't open.

    can you give a sample?THX


    The new address is:http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx
    In the bottom of the page, you have the section Exposing Web Services from an ASP.NET Web Page.

    Basically, what you need to do is to create a static method and apply the [WebMethod] attribute to it.

    [WebMethod]public static string EchoString(string name) {return"Called by " + name +".";}
    HTH,
    Maíra

    Monday, March 26, 2012

    Calling a JavaScript function after return from callback in UpdatePanel

    Hi all.

    I am trying to solve this focusing problem inherint in Atas, I have a 90% generic solution, but am missing the last piece to the puzzle.

    I need a way to invoke a JavaScript function after the UpdatePanel has returned from a server callback.

    I know this is pretty simple to do without an UpdatePanel, unfortunately I am kinda tied into the UpdatePanel.

    Any help??

    Thanks

    Hi,

    I had the same problem. This is the solution I could found.
    See this post for reference:http://forums.asp.net/thread/1290506.aspx

    function pageLoad()
    {
    $object("_PageRequestManager").propertyChanged.add(BindOnLoad);
    }


    function BindOnLoad(sender, args)
    {

    if (args.get_propertyName() == "inPostBack"){
    if (!$object("_PageRequestManager").get_inPostBack()){
    AtlasPostBack();}
    }
    }

    function AtlasPostBack()
    { //Runs at every postback. This allows us to run things that need to be taken care of
    //after postbacks

    alert("partial postback is done");
    }


    Thanks,

    I also found that from the server side, registering a script as a startup script will make it fire on every callback.

    Page.ClientScript.RegisterStartupScript.

    Call Web Service : can not return dataset

    Hi,

    I got an error : "A circular reference was detected while serializing an object of type 'System.Globalization.Cultureinfo' when returning a dataset variable. It didn't happen when returning string.

    It also run smoothly when using PageMethods of Atlas.

    What's wrong with the code :

    <Microsoft.Web.Script.Services.ScriptService()> _Public Class EmpServiceInherits System.Web.Services.WebServiceDim cnHimalayaAs New SqlConnection( _ ConfigurationManager.ConnectionStrings("HimalayaConnectionString").ConnectionString) <WebMethod()> _Public Function GetData(ByVal SearchCategoryAs String,ByVal NIKAs String)As Data.DataSetDim strSQLAs String Select Case SearchCategoryCase"Experience" strSQL = _"SELECT JobTitle,Company,Period,JobDesc DeptName FROM Ht_HRD_Experience " & _"WHERE NIK ='" & NIK & "'" Case "Training" strSQL = _ "SELECT Training,Category,Year,Host,Location FROM Ht_HRD_Training" & _ "WHERE NIK ='" & NIK & "'"Case"Education" strSQL = _"SELECT Education,School,Subject,YearGraduate FROM Ht_HRD_EmpEducation " & _ "WHERE NIK ='" & NIK & "'"End Select Dim sqlDaAs New SqlDataAdapter(strSQL, cnHimalaya)Dim dsDataAs New Data.DataSetIf cnHimalaya.State = Data.ConnectionState.ClosedThen cnHimalaya.Open()End If Try sqlDa.Fill(dsData)Return dsDataCatch exAs SqlExceptionThrow (New ApplicationException(ex.Message))Finally cnHimalaya.Close() dsData.Dispose()End Try End Function

    thanks.

    The problem is the DataSet is not natively supported by the JavaScriptSerializer.
    In order to return a DataSet, you need to implement and register a custom converter for the DataSet in the config file.
    There is a DataTable converter that comes with the ASP.NET 2.0 AJAX Futures November CTP that you can try to use.

    HTH,

    Maíra


    Thanks.

    Do you have article that expalin more detail with example how to do that?

    Rgds


    Instead of the dataset-- why don't you just return Xml?

    That's good idea. I'll use it for the next project because there is a lot of code i have to change for the current project.

    thanks anyway.


    Instead of the dataset-- why don't you just return Xml?

    Eh because using XML is pretty much a pain to use in JavaScript? <s> Wno wants to parse XML on the client side when you could instead get an object back instead?

    As to the DataTable converter it's broken in Beta 2 - it's still in Beta 2 but it's returning a bogus object which appears to be an internal object. It is possible to use the converter and grab the JSON it generates but this will likely change in the future so it's probably not a good idea to use.

    Here's an example (Client Code):

     function GetCustomerTable_Callback(Result) { var List = ListControl.get_element();// retrieve raw DOM element // *** This is a HACK workaround AJAX Beta 1 until Microsoft brings back a real // *** DataTable Converter currently it contains a string property that has be eval'd // *** String has trailing ( that must be trimmed off var Text= Result.dataArray.substring(0,Result.dataArray.length -1); var Table = eval( Text);// *** Clear the list firstfor (x=List.options.length-1; x > -1; x--) { List.remove(0); }for (x=0; x < Table.length; x++ ) { var Row = Table[x];// Mozilla needs to assign var option = document.createElement("option"); option.text = Row.CompanyName; option.value = Row.CustomerId;if ( window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) List.add(option);else List.add(option,null); } }
     

    On the server (WebService or PageMethod):

     [WebMethod]public DataTable GetCustomerTable() { busCustomer Customer =new busCustomer();if (Customer.GetCustomerList() < 0)return null; DataTable dt = Customer.DataSet.Tables["TCustomerList"];return dt; }

    You also need to register the DataTableConverter:

    <microsoft.web><scripting><webServices><!-- Uncomment this line to customize maxJsonLength and add a custom converter --><jsonSerialization maxJsonLength="50000"><converters><add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter"/></converters></jsonSerialization></webServices></scripting></microsoft.web>
     
    +++ Rick -- 


    I just downloaded AJAX v1.0 and now I get the circular reference error. I had the following code but I don't know what I have to change it to for my code to work properly.

    <jsonSerialization maxJsonLength="50000"><converters><add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter"/></converters></jsonSerialization>

    Anyone have any ideas? Thanks.


    Sorry, this does work. I forgot to download the January Futures CTP.

    You usually get this error when you try to serialize a DataTable that has no custom converter registered for it.

    The Ajax v1.0 does not contain the converters for the DataTable, they are part of the ASP.NET AJAX Futures January CTP. You need to install this and add a reference to in in your project.

    Have you done this?

    Maíra


    Hi folks,

    I'm getting the same problem and am "stuck", so I appreciate some help !

    I installed the ASP.NET AJAX Futures January CTP msi file.

    I added a reference to my \BIN

    C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Futures January CTP\v1.0.61025\Microsoft.Web.Preview.dll

    I put this in the web.config:

    <system.web.extensions>
    <scripting>
    <webServices>
    <jsonSerialization maxJsonLength="50000">
    <converters>
    <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter"/>
    </converters>
    </jsonSerialization>
    </webServices>

    But still no go...

    Do I have to MERGE the web_CTP.config with my standard AJAX 1.0 web.config or replace it entirely ?

    It seems fairly complex to do so. Is their a pre-existing AJAX 1.0 / Jan CTP combined web.config available ?

    Thanks, LA Guy


    Hi again,

    I missed these settings but still no go.

    <jsonSerialization maxJsonLength="50000">
    <converters>
    <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"/>
    <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"/>
    <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"/>
    </converters>
    </jsonSerialization>

    Thanks, LA Guy


    I'm getting the same problem and am "stuck", thk


    Guys I'm getting it working fine with the January CTP with the

    <system.web.extensions>
    <scripting>
    <webServices>
    <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
    <jsonSerialization>
    <!--<jsonSerialization maxJsonLength="500">-->
    <converters>
    <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </converters>
    </jsonSerialization>

    Config setting and the reference added to the Preview dll.

    Can we assume these implementations would be included in the future MS Ajax releases bcoz I'm going to use these JSON converters for a real product.


    I am running the latest AJAX 1.0 product set. When I apply the changes as mentiond above, I no longer am able to access my webmethod. I get a javascript error that states that method is undefined? when I comment the section above, I get circular reference encountred (since I am trying to return a datatable)

    What am I doing wrong?

    Saturday, March 24, 2012

    Call ASP.NET web service and return JSON using only html/javascript

    I've implmented a pretty basic webservice as per below. I did a quick test in ASP.NET AJAX using the ScriptManager and it returned JSON-formatted data perfectly. I am now trying to do the same using just html/javascript with the XmlHttpRequest object.

    Currently I've assigned the context-type to the XmlHttpRequest as is apparently required, and the webservice is "working", but only returning xml.Surprise

    I'd really appreciate any help - or maybe even a better way to access the ASP.NET web service externally (i.e. outside of ASP.NET). Thanks.

    PART A: ASP.NET Webservice snippet

    [WebService(Namespace = "http://microsoft.com/webservices/";
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class ScriptingService : OrYxBaseWebService {
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public ScriptPersonRoleList GetActiveCategoryManagers() {
    OrYxAppStatus myStatus = BFManager.GetInstance().CreateStatus(GetDefaultRequest());
    return BFManager.ScriptingBF.GetActiveCategoryManagers(ref myStatus);
    }
    }

    PART B: Index html

    <html>
    <head>
    <title>Ajax Test Drive</title>
    <script type="text/javascript" language="javascript">

    function makePOSTRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
    // set type accordingly to anticipated content type
    // http_request.overrideMimeType('text/xml');
    http_request.overrideMimeType('text/html');
    }
    } else if (window.ActiveXObject) { // IE
    try {
    http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    alert("not good at all..");
    }
    }
    }
    if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
    }

    http_request.onreadystatechange = confirmResponse;
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-Type", "application/json");

    http_request.send(parameters);
    }

    function confirmResponse() {
    if (http_request.readyState == 4) {
    if (http_request.status == 200) {
    result = http_request.responseText;
    document.getElementById('databox').innerHTML = result;
    alert('Response:\n\n' + result);
    } else {
    alert('There was a problem with the request.');
    }
    }
    }

    function getData() {
    var url = 'http://localhost/TVScriptingWebService/TVScripting.asmx/GetActiveCategoryManagers';
    var request = makePOSTRequest(url, "");
    }
    </script>

    </head>
    <body onload="getData()">
    <div style="width: 600px; padding: 10px; border: 1px solid;" align="center">
    Test page</div>
    <br>
    <div id="databox">
    </div>
    <br>
    </body>
    </html>

    What format do you want data in now?


    I am wanting JSON not XML.


    use text/json rather than application/json


    Thanks for the response, I tried adding the following lines, but they all still return only xml as the responseText

    http_request.setRequestHeader('Content-Type','text/json');


    Could i again confirm that the webservice is actually returning JSON data?


    The only time I have seen the webservice returns JSON data is when its called from within ASP.NET AJAX pages using the ScriptManager - which I don't want to do because these services are ultimately going to be called from a php application..

    I am trying to call it using using only javascript/html and cannot get it to return JSON - only xml

    Environment: ASP.NET 2.0, AJAX ASP.NET RC1. Tested on IIS5.1 and IIS6

    Thanks


    Well again it could be an inadvertant policy issue where microsoft doesnt want people to use other products just like datatable which is not returned as webservice. But you can always convert xml to json.

    Let me see your code for consuming page in .net


    Hi naturehermit,

    Thanks again. You're right I could parse the xml into Json within the client, however I think that would eliminate one of the main advantages of using JSON..Wink

    I couldn't get it to work so I've implemented my own IHttpHandlerFactor and IHttpHandler classes which was pretty easy. They now intercept the webservice calls and check whether use my classes, which return JSON using the JavaScriptSerializer, or the generic WebServiceHandlerFactory().

    Currently the flag I've decided on is if there is an "application/OrYxJson" within the Context-Type property of the request. If this property is set, JSON gets returned, otherwise you get good old SOAP.

    Early days, but so far so good..


    Good luck mate, let me know if i could be of any help. Its always good to share your experiences


    Yep agreed and willdo. Thanks.


    naturehermit:

    What format do you want data in now?


    ?


    Hi,

    I ran into same issue where I specified in the webservice JSON and yet XML was returned. Anyway, I found ot that it actually returns JSON. Try running fiddler to intercept the response from the webservice and you'll see the JSON string. Ignore the "_type".

    Thanks