Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Cega86

Jquery + asp.net

Recommended Posts

É possível chamar do lado cliente, métodos na minha página asp(servidor) com jquery utilizando o framework 2.0(visual studio 2005)?ou só à partir do 3.5(visual studio 2008)?

Compartilhar este post


Link para o post
Compartilhar em outros sites

No caso a versão do VS não influencia em nada e neste exemplo e uma requisião json a um WebService. no seu caso tb é um webservice?

Compartilhar este post


Link para o post
Compartilhar em outros sites

No meu caso é um web site normal porém o método está marcado como [web method].

No exemplo ele também usou um web site normal ou não?

estou usando o plugin fireBug do fire fox para testar e ele envia a solicitação porém não consigo pegar a resposta do servidor.

Compartilhar este post


Link para o post
Compartilhar em outros sites

No exemplo ele não esta chamando um metodo de uma classe normal e sim de um WebService, é pq ele não mostrou tudo, pra você fazer isso você tera q criar um web service, no VS quando você seleciona adicionar novo item, tem lá WebService e é nesse item que você deve colocar seu metodo.

Compartilhar este post


Link para o post
Compartilhar em outros sites

beleza eu já criei o web service mas quando adicionei ele no projeto ele ficou dentro da pasta app_code.

Então eu mudei a url indicando o caminho correto conforme o código a baixo.

 

<script type ="text/javascript" >
    $(document).ready(function(){
    $("#resultado").click (function(){
    $.ajax({
    type:"POST",
    url: "App_Code/WebService.cs/GetDate",
    data: "{}",
    contentType: "application/json; charset = utf-8",
    dataType: "json",
    success: function(msg){
    $("#resultado").text(msg);
    } 
    });
    });
    });
 
    </script>

Ele faz a solicitação continua sem retornar.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Criei o método como static e declarei o webmethod porém ainda não funciona.

meu código está assim:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script src="js/jquery-1.3.2.min.js" type ="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id = "resultado">
    Clique aqui
    </div>
    </form>
    <script type ="text/javascript" >
    $(document).ready(function(){
    $("#resultado").click (function(){
    $.ajax({
    type:"POST",
    url: "Default.aspx/GetDate",
    data: "{}",
    contentType: "application/json; charset = utf-8",
    dataType: "json",
    success: function(msg){
    $("#resultado").text(msg);
    } 
    });
    });
    });
 
    </script>
</body>
</html>

e o Default.aspx.cs:

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page 
{
    
    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }

    
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde Cega86, então o metodo do webserver não pode estar dentro de uma pagina como essa _default e sim dentro d uma classe que seja um webservice.

 

[WebService(Namespace = "[url="http://tempuri.org/"]http://tempuri.org/[/url]")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : WebService
{
    [WebMethod] 
    public static string GetDate() 
    {         return DateTime.Now.ToString(); 
    }
}

 

Quanto ao caminho eu creio que não precisa informar App_Code não, pq mesmo o arquivo cs estando lá dentro a referencia ao serviço esta na raiz.

Compartilhar este post


Link para o post
Compartilhar em outros sites

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script src="js/jquery-1.3.2.min.js" type ="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id = "resultado">
    Clique aqui
    </div>
    </form>
    <script type ="text/javascript" >
    $(document).ready(function(){
    $("#resultado").click (function(){
    $.ajax({
    type:"POST",
    url: "WebService.cs/GetDate",
    data: "{}",
    contentType: "application/json; charset = utf-8",
    dataType: "json",
    success: function(msg){
    $("#resultado").text(msg);
    } 
    });
    });
    });
 
    </script>
</body>
</html>

WenService

 

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }
    
}

quando uso o fireBug para debugar ele a resposta da solicitação é essa:

 

<html>

    <head>

        <title>This type of page is not served.</title>

        <style>

         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 

         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}

         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}

         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }

         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }

         pre {font-family:"Lucida Console";font-size: .9em}

         .marker {font-weight: bold; color: black;text-decoration: none;}

         .version {color: gray;}

         .error {margin-bottom: 10px;}

         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

        </style>

    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/testeJquery' Application.<hr width=100% size=1 color=silver>

</H1>

            <h2> <i>This type of page is not served.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>The type of page you have requested is not served because it has been

 explicitly forbidden.     Please review the URL below and make sure that it is spelled

 correctly.

            <br><br>

            <b> Requested URL: </b>/testeJquery/WebService.cs/GetDate<br><br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET

 Version:2.0.50727.3074

            </font>

    </body>

</html>

<!-- 

[HttpException]: Path '/testeJquery/WebService.cs/GetDate' is forbidden.

   at System.Web.HttpForbiddenHandler.ProcessRequest(HttpContext context)

   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute

()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

-->

oque pode está errado?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tenta alterar isso:

[WebService(Namespace = "[url="http://tempuri.org/"]http://tempuri.org/[/url]")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

para

[WebService(Namespace = "[url="http://tempuri.org/"]http://tempuri.org/[/url]")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ivan, esse cara [scriptService] pertence ao namespace System.Web.Script.Services e pelo que pude ver ele é do framwork 3.5 e euestou com o 2.0.

Por isso não consigo usar esse cara, existe outra forma?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Então não precisa ser dentro de um web service?

coloquei o break point e ele não ta passando por ele.

meu código ta assim:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script src="js/jquery-1.3.2.min.js" type ="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id = "resultado">
    Clique aqui
    </div>
    </form>
    <script type ="text/javascript" >
    $(document).ready(function(){
    $("#resultado").click (function(){
    $.ajax({
    type:"POST",
    url: "Default.aspx/GetDate",
    data: "{}",
    contentType: "application/json; charset = utf-8",
    dataType: "json",
    success: function(msg){
    $("#resultado").text(msg);
    } 
    });
    });
    });
 
    </script>
</body>
</html>

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;


    public partial class _Default : System.Web.UI.Page
    {
      
        [WebMethod]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }


    }

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde Cega86, falei com o Quitelab sobre essa questão e eu apanhei muito quanto a isso a um tempo atrás e resolvi usando webservice, e achava q não funcionava, mas realmente pode deixar seu metodo dentro do formulário mesmo. e o que esta erado é simplesmente um msg.d aqui ->

$("#resultado").text(msg);
repare que no proprio link q você pstou esta assim ->
$(#resultado").text(msg.d);
eu testeia qui e funcionou perfeitamente!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pois é cara, no link q eu coloquei o autor explica e esse "d" é uma segurança do framwork 3.5 e que se estiver usando o 2.0 que é o meu caso não precisa usar o "d" colocando somente (msg).

por isso no primeiro post eu perguntei se é possível chamar os métodos usando jquery no framework 2.0.

será que não está funcionando aqui por causa disso?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pois é eu testei aqui no 2.0 e a resposta no FireBub foi com sucesso, porém não exibiu o resultado na div não, debugando ele nem passa pelo metodo

Compartilhar este post


Link para o post
Compartilhar em outros sites

Acabei de testar no 3.5 dei um alert e funcionou:

 

   <script type="text/javascript">
   $(document).ready(function(){
       $("#resultado").click (function(){
           $.ajax({
               type:"POST",
               url: "BrunoTeste.aspx/GetDate",
               data: "{}",
               contentType: "application/json; charset = utf-8",
               dataType: "json",
               success: function(msg){
                   alert(msg.d);
                   //$("#resultado").text(msg);
               } 
           });
       });
   }); 
   </script>

 

Abraços...

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.