.NET Simple Form通过AJAX和JQUERY提交

时间:2022-11-24 12:49:11

I've got the flow all worked out thanks to balexandre and rtiq. My .ashx file is being called so I know a portion of the code is working and it is alerting me to an error. When I trace the .NET, the variables pulled in via context.Request["email"] and context.Request["optin"] are NULL.

由于balexandre和rtiq,我得到了流量。我的.ashx文件被调用,所以我知道一部分代码正在运行,它提醒我一个错误。当我跟踪.NET时,通过context.Request [“email”]和context.Request [“optin”]引入的变量为NULL。

I know there's something wrong but I can't see it. I've re-edited this post to have the latest code.

我知道有些不对劲但我看不到它。我已经重新编辑了这篇文章,以获得最新的代码。

jQuery in HEAD

<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>

CodeBehind in a .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;
        }
    }
}

The form and elements are acting properly. We are just getting this NULL values and not being able to insert. The ajax is calling the .ashx file properly and the file is compiling, the requested variables are null.. The previous help was awesome, if anyone could help me get this last kink out, you would get a gold star for the day! :)

表格和元素表现得很好。我们只是获取此NULL值而无法插入。 ajax正在调用.ashx文件并且文件正在编译,请求的变量为空。之前的帮助很棒,如果有人能帮我解决这个问题,你会得到一个金星! :)


After some searching offline in books, this finally worked for me in concjunction with balexandres .aspx method:

经过一些书籍离线搜索后,这最终与balexandres .aspx方法结合使用:

SOLUTION

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

4 个解决方案

#1


1  

  • create a new folder in your website root called asynchronous
  • 在您的网站根目录中创建一个名为asynchronous的新文件夹

  • create a new aspx page called addEmail.aspx and delete all HTML except the 1st line
  • 创建一个名为addEmail.aspx的新aspx页面并删除除第1行以外的所有HTML

  • inside that addEmail.aspx you place your code behind, like:
  • 在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");
}
  • in your main page that has the .ajax() call change the url property to

    在您的主页面中,具有.ajax()调用将url属性更改为

    url: "/asynchronous/insertEmail.aspx",

You will have in your msg in success: function (msg) {} the string email inserted

您将在msg中获得成功:function(msg){}插入的字符串电子邮件

This is what I always do, though, instead of creating an ASPX Page, I use ASHX (Generic Handler) page that does not contain any ASP.NET Page Cycle (faster to load) and it's a simple page.

这是我经常做的,但是,我使用的ASHX(Generic Handler)页面不包含任何ASP.NET页面循环(加载速度更快)而不是创建ASPX页面,而且它是一个简单的页面。


if you want to use a Generic Handler instead, create inside asynchronous folder a file called inserEmail.ashx and the full code would be:

如果你想使用Generic Handler,在异步文件夹里面创建一个名为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;
        }
    }
}

and, remember to change your url property to url: "/asynchronous/insertEmail.ashx",

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


from your comment I realized that your data property was also not correct.

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

the correct is:

正确的是:

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

your full ajax call should be:

你的完整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); 
    }
});

and your Response.Write in the generic handler should pass a JSON string as well

并且通用处理程序中的Response.Write也应传递JSON字符串

so, change tgis context.Response.Write("email inserted"); into context.Response.Write("{d:'email inserted'});

所以,改变tgis context.Response.Write(“email inserted”); into context.Response.Write(“{d:'email inserted'});

that's all.

#2


1  

 $("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.

#3


0  

You don't have a form in your html code and since you may not use submit. Use click instead as rciq wrote.

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

#4


0  

Try changing this:

尝试改变这个:

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

To this:

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

Also you must remember that the ID of the ASP.NET server control is not the same as the rendered DOM control ID. This might be the reason why your alert does not fire. If you write the client script on the same page as the server control, you can 'render' the ClientID inside a script tag this way:

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

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

Another thing. If you use jQuery selections in HEAD scripts they might be firing too early to find the controls. You should run them after the DOM controls are created. One thing to accomplish that is to use the 'ready' event:

另一件事。如果在HEAD脚本中使用jQuery选择,则可能会过早地找到控件。您应该在创建DOM控件后运行它们。要完成的一件事是使用'ready'事件:

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

#1


1  

  • create a new folder in your website root called asynchronous
  • 在您的网站根目录中创建一个名为asynchronous的新文件夹

  • create a new aspx page called addEmail.aspx and delete all HTML except the 1st line
  • 创建一个名为addEmail.aspx的新aspx页面并删除除第1行以外的所有HTML

  • inside that addEmail.aspx you place your code behind, like:
  • 在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");
}
  • in your main page that has the .ajax() call change the url property to

    在您的主页面中,具有.ajax()调用将url属性更改为

    url: "/asynchronous/insertEmail.aspx",

You will have in your msg in success: function (msg) {} the string email inserted

您将在msg中获得成功:function(msg){}插入的字符串电子邮件

This is what I always do, though, instead of creating an ASPX Page, I use ASHX (Generic Handler) page that does not contain any ASP.NET Page Cycle (faster to load) and it's a simple page.

这是我经常做的,但是,我使用的ASHX(Generic Handler)页面不包含任何ASP.NET页面循环(加载速度更快)而不是创建ASPX页面,而且它是一个简单的页面。


if you want to use a Generic Handler instead, create inside asynchronous folder a file called inserEmail.ashx and the full code would be:

如果你想使用Generic Handler,在异步文件夹里面创建一个名为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;
        }
    }
}

and, remember to change your url property to url: "/asynchronous/insertEmail.ashx",

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


from your comment I realized that your data property was also not correct.

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

the correct is:

正确的是:

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

your full ajax call should be:

你的完整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); 
    }
});

and your Response.Write in the generic handler should pass a JSON string as well

并且通用处理程序中的Response.Write也应传递JSON字符串

so, change tgis context.Response.Write("email inserted"); into context.Response.Write("{d:'email inserted'});

所以,改变tgis context.Response.Write(“email inserted”); into context.Response.Write(“{d:'email inserted'});

that's all.

#2


1  

 $("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.

#3


0  

You don't have a form in your html code and since you may not use submit. Use click instead as rciq wrote.

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

#4


0  

Try changing this:

尝试改变这个:

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

To this:

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

Also you must remember that the ID of the ASP.NET server control is not the same as the rendered DOM control ID. This might be the reason why your alert does not fire. If you write the client script on the same page as the server control, you can 'render' the ClientID inside a script tag this way:

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

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

Another thing. If you use jQuery selections in HEAD scripts they might be firing too early to find the controls. You should run them after the DOM controls are created. One thing to accomplish that is to use the 'ready' event:

另一件事。如果在HEAD脚本中使用jQuery选择,则可能会过早地找到控件。您应该在创建DOM控件后运行它们。要完成的一件事是使用'ready'事件:

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