【问题标题】:.NET Simple Form Submit via AJAX and JQUERY.NET 简单表单通过 AJAX 和 JQUERY 提交
【发布时间】:2011-06-13 12:26:08
【问题描述】:

感谢 balexandre 和 rtiq,我的流程全部搞定了。正在调用我的 .ashx 文件,因此我知道部分代码正在运行,它会提醒我出现错误。当我跟踪 .NET 时,通过 context.Request["email"] 和 context.Request["optin"] 提取的变量为 NULL。

我知道有问题,但我看不到。我重新编辑了这篇文章以获得最新的代码。

在 HEAD 中的 jQuery

​​>
<script type="text/javascript">
    $(document).ready(function () {
        $(".submitConnectButton").click(function (evt) {
            evt.preventDefault();
            alert("hello click");

            alert($(".emailConnectTextBox").val());

            $.ajax({
                type: "POST",
                url: "/asynchronous/insertEmail.ashx",
                data: "{email: '" + $(".emailConnectTextBox").val() + "',optin: '" + $(".connectCheckbox").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) { alert(msg.d); },
                error: function (msg) { alert('Error:' + msg); }
            });
        });
    });
</script>

HTML

<div class="emailConnect">
    <asp:TextBox runat="server" ID="TextBox1" CssClass="emailConnectTextBox" BorderStyle="Solid"></asp:TextBox>
              <asp:ImageButton id="connectButton" CssClass="submitConnectButton" runat="server" ImageUrl="~/Images/submit_btn.png" /><br />
    <asp:CheckBox Checked="true" id="checkbox1" runat="server" CssClass="connectCheckbox" />
</div>

.ashx 中的代码隐藏

public class insertEmail : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string strConnection = System.Configuration.ConfigurationManager.AppSettings["SQLConnectString"].ToString();

        string email = context.Request["email"],
               optin = context.Request["optin"];

        string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "','" + optin.ToString() + "')";
        SqlConnection Conn = new SqlConnection(strConnection); 
        SqlCommand Command = new SqlCommand(strSQL, Conn);
        Conn.Open();
        Command.ExecuteNonQuery(); 
        Conn.Close(); 
        context.Response.ContentType = "text/plain"; 
        context.Response.Write("email inserted");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

表单和元素运行正常。我们只是得到这个 NULL 值并且无法插入。 ajax 正在正确调用 .ashx 文件并且文件正在编译,请求的变量为空。以前的帮助很棒,如果有人可以帮助我解决最后一个问题,您将获得当天的金星! :)


在书籍中离线搜索后,这终于与balexandres .aspx方法一起为我工作了:

解决方案

$.post("/asynchronous/addEmail.aspx", {email: $(".emailConnectTextBox").val(),optin: $(".connectCheckbox").is(':checked')}, function(data) { alert('Successful Submission');});

【问题讨论】:

  • 到目前为止,我已经使用了 balexandre 和 rciq 的答案来使其正确流动。我现在只是在 ajax 发送正确的内容而不是空值时遇到问题。

标签: jquery .net sql ajax


【解决方案1】:
  • 在您的网站根目录中创建一个名为asynchronous 的新文件夹
  • 创建一个名为 addEmail.aspx 的新 aspx 页面并删除除第一行以外的所有 HTML
  • addEmail.aspx 中,您将代码放在后面,例如:

.

public void Page_Load(...) 
{
    insertEmail();
}

public void inserEmail() {

    string email = Request["email"],
           optin = Request["optin"];

    string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
    SqlConnection Conn = new SqlConnection(strConnection);
    SqlCommand Command = new SqlCommand(strSQL, Conn);
    Conn.Open();
    Command.ExecuteNonQuery();
    Conn.Close();

    // Output
    Response.Write("email inserted");
}
  • 在您调用 .ajax() 的主页中,将 url 属性更改为

    url: "/asynchronous/insertEmail.aspx",

您将在success: function (msg) {} 中的msg 中拥有字符串email inserted

这是我一直做的,不过,我没有创建 ASPX 页面,而是使用不包含任何 ASP.NET 页面周期(加载速度更快)的 ASHX(通用处理程序)页面,它是一个简单的页面。


如果您想改用Generic Handler,请在asynchronous 文件夹中创建一个名为inserEmail.ashx 的文件,完整代码为:

public class insertEmail : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string email = context.Request["email"],
               optin = context.Request["optin"];

        string strSQL = "INSERT INTO Emails (emailAddress,optIn) VALUES('" + email.ToString() + "', optin)";
        SqlConnection Conn = new SqlConnection(strConnection);
        SqlCommand Command = new SqlCommand(strSQL, Conn);
        Conn.Open();
        Command.ExecuteNonQuery();
        Conn.Close();

        context.Response.ContentType = "text/plain";
        context.Response.Write("email inserted");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

并且,记得将您的 url 属性更改为 url: "/asynchronous/insertEmail.ashx",


从您的评论中,我意识到您的 data 属性也不正确。

正确的是:

data: { 
        "email" : $(".emailConnectTextBox").val(), 
        "optin" : $(".connectCheckbox").val() },

您的完整 ajax 调用应该是:

$.ajax({
    type: "POST",
    url: "/asynchronous/insertEmail.ashx",
    data: { 
        "email" : $(".emailConnectTextBox").val(), 
        "optin" : $(".connectCheckbox").val() 
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) { 
        alert(msg.d); 
    },
    error: function (msg) { 
        alert('Error:' + msg.d); 
    }
});

您在通用处理程序中的 Response.Write 也应该传递一个 JSON 字符串

所以,将 tgis context.Response.Write("email inserted"); 更改为 context.Response.Write("{d:'email inserted'});

就是这样。

【讨论】:

  • 我使用您的解决方案来处理传入的 ajax,即 .ashx 文件。它正确触发,但请求对象为空。我假设数据没有被正确发送。
  • 字符串 email = context.Request["email"], optin = context.Request["optin"];
  • 它抓取空值......我的 ajax 调用中有什么不正确的吗?
  • 是的,您说得对,您的data 也不正确...我编辑了答案,为您提供了正确的数据线,您需要将其更改为
  • 它仍然返回为空...我使用母版页是否重要?似乎调用后面的代码就好了。只有变量没有被传递。感谢您一直以来的帮助。
【解决方案2】:
 $("button").click(function(){
 var content = new Object();
 content.email = $("#email").val();
 content.option = $("#checkbox").val();
 content = JSON.stringify(content);


 $.ajax({
        async: false,
        type: "POST",
        url: aspxPage + "/" + function, //make sure root is set proper.
        contentType: "application/json;",
        data: content,
        dataType: "json",
        success: successFunction,
        error: errorFunction
    });
    });


    //Make sure the form is posted ..which is needed for ajax to submit.
    //the data part in code behind seems ok.

【讨论】:

  • 当您说“确保表单已发布”时,您的意思是除了 type:“POST”设置之外的任何其他内容吗?
【解决方案3】:

您的 html 代码中没有表单,因为您可能不使用提交。 如 rciq 所写,使用 click 代替。

【讨论】:

    【解决方案4】:

    尝试改变这个:

    $("#connectButton").submit(function () {
        alert("hello click");
        (...)
    

    到这里:

    $("#connectButton").click(function (evt) {
        evt.preventDefault();
        alert("hello click");
        (...)
    

    您还必须记住,ASP.NET 服务器控件的 ID 与呈现的 DOM 控件 ID 不同。这可能是您的警报没有触发的原因。如果您在与服务器控件相同的页面上编写客户端脚本,则可以通过这种方式在脚本标记内“呈现”ClientID:

    $("<%= connectButton.ClientID %>").click( ...
    

    另一件事。如果您在 HEAD 脚本中使用 jQuery 选择,它们可能会过早触发而无法找到控件。您应该在创建 DOM 控件后运行它们。要做到这一点的一件事是使用“就绪”事件:

    http://api.jquery.com/ready/

    【讨论】:

    • 我首先尝试您的示例,因为它似乎直接解决了我正在尝试的问题。
    • 好的,就我的元素而言,它会抓取电子邮件地址并提醒我上述所有解决方案都有效。现在,ajax 部分似乎没有触发代码隐藏的 Web 方法..
    • 我很高兴它成功了。至于 .ashx 代码,这是一个不同的问题,我确信 balexandre 的答案是完整的,并将帮助您完成其余工作:)
    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 2012-03-22
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多