【问题标题】:Display alter message in Webmethod在 Web 方法中显示更改消息
【发布时间】:2016-03-10 11:53:26
【问题描述】:
[webMthod]

HttpContext.Current.Response.Write("<script>alert('your messsage')</script>"); 

【问题讨论】:

  • Write("");注意空格,没有它们无法提交
  • 那么,您能否提供更多关于您想要完成的内容的信息?

标签: c# asp.net webmethod


【解决方案1】:

如果你对 web 方法进行 ajax j 查询调用,你可以在失败和成功方法中发出警报,只从你想要打印的 web 方法返回数据。

<script type = "text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "WebForm3.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script> 

  [System.Web.Services.WebMethod]
        public static string GetCurrentTime(string name)
        {

            return "messaage";
        }

如果您正在做其他事情或者您正在做与此不同的事情,请告诉我。

【讨论】:

    【解决方案2】:

    您的意思是除了方法返回的数据之外,您还需要一种显示替代消息的方法?

    为此,我使用了一个类,我在其中嵌入了我想要返回的数据。这样,所有服务方法都返回一个公共类,其中包含您要传递的消息以及调用者实际需要的数据。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    public class Service_Response
    {
        public string Message { get; set; }
        public dynamic Data { get; set; }
    
        public Service_Response()
        {
    
        }
    
        public Service_Response(string msg)
        {
            this.Message = msg;
            this.Data = null;
        }
    
        public Service_Response(string msg, dynamic obj)
        {
            this.Message = msg;
            this.Data = obj;
        }
    
        public Service_Response(string msg, object obj, Type obj_type)
        {
            this.Message = msg;
            this.Data = Convert.ChangeType(obj, obj_type);
        }
    }
    

    要使用它,

    [WebMethod()]
    public static Service_Response GetHelloWorld() {
          return new Service_Response("hello world", true);
    }
    //or
    [WebMethod()]
    public static Service_Response GetHelloWorld(int i) {
          return new Service_Response("hello world" + i);
    }
    //or
    [WebMethod()]
    public static Service_Response GetHelloWorld(string name) {
          var data = DateTime.Now;
          return new Service_Response("hello world from " + name, data);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 2012-03-23
      • 1970-01-01
      相关资源
      最近更新 更多