【问题标题】:C# Webmethod public static void message back to JqueryC# Webmethod public static void 消息返回给 Jquery
【发布时间】:2015-06-09 19:41:49
【问题描述】:

您好,我需要向 Jquery 返回一条消息。我的 webmethod 和 SQL 脚本做他们的事情,我现在不需要担心异常错误。

*重要的消息是 count > 0 ,因为这将通过 Jquery Alert 告诉用户电子邮件已经注册。

[WebMethod]
[ScriptMethod]
public static void SaveUser(Saved user)
{

    string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {

        try
        {
            using (SqlCommand cmd = new SqlCommand("select count(*)from TestTable2 where Email=@Email"))
            {

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@Email", user.Email);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();

                int count = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
                if (count > 0)
                {
                    // ...message email taken!
                }
                else
                {
                    // now do Insert!
                }
            }

        }

        catch (Exception E)
        {

            StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
            sw.WriteLine(E.Message + user.Email);

            sw.Close();
            sw.Dispose();

            throw new Exception(E.Message);

        }
    }
}

$.ajax({
            type: "POST",
            url: "my_dev3.aspx/SaveUser",
            data: '{user: ' + JSON.stringify(user) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert('OK!');
            },

            error: function () {
                alert('Error!')
            }
        });
        return false;

【问题讨论】:

  • 因此,将返回类型从 void 更改为您需要返回的任何数据的类型(字符串?新类?),然后返回。

标签: c# jquery


【解决方案1】:

试试这个:

[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string SaveUser(Saved user)
{
    string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {

        try
        {
            using (SqlCommand cmd = new SqlCommand("select count(*)from TestTable2 where Email=@Email"))
            {

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@Email", user.Email);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();

                int count = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
                if (count > 0)
                {
                    return new JavaScriptSerializer().Serialize(new { Message = "Email Taken"});
                }
                else
                {
                    return new JavaScriptSerializer().Serialize(new { Message = "Email Inserted"});

                }
            }

        }
        catch (Exception E)
        {

            StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\jQuery_AJAX_Database\error.txt", true);
            sw.WriteLine(E.Message + user.Email);

            sw.Close();
            sw.Dispose();

            throw new Exception(E.Message);
            return new JavaScriptSerializer().Serialize(new { Message = "Error Occured"});

        }
    }
}

AJAX

$.ajax({
            type: "POST",
            url: "my_dev3.aspx/SaveUser",
            data: '{user: ' + JSON.stringify(user) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                    alert(data.Message);
            },

            error: function (data) {
                alert(data.Message)
            }
        return false;
});

【讨论】:

  • 谢谢你的帖子!发生的几件事(不是)首先是 catch 异常中的返回,其次是返回的新消息警报是未定义的。尽管我通过 return 和 success: function (result) { var msg = result.hasOwnProperty("d") 得到了消息,但您已经提供了帮助?结果.d:结果;警报(味精); },
  • [object Object] {...} d"{"Message":"Email Inserted"}"
  • 在那个对象里面应该有那个Message,我提到的方法是正确的方法。试试这个var datas=jQuery.parseJSON(data);然后alert(datas.Message);或者只是console.log(datas)然后检查你得到什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2019-05-28
  • 2019-07-15
  • 2011-08-03
  • 2011-02-23
  • 1970-01-01
  • 2015-05-30
相关资源
最近更新 更多