简体   繁体   中英

Retrieve a value from jQuery/JavaScript/AJAX to add to database (ASP.NET/C#)

I want to create a simple form with some textboxes as well as a five star rating feature ( http://rateit.codeplex.com/ ). When the submit button is clicked, the data in the fields should get added to a database.

The textboxes are not a problem but I'm having trouble trying to 'retrieve' the value from the star rating.

I tried a workaround by outputting the value into a label once a rating has been selected, however, when writing to the database, no values get sent.

HTML: Your rating:

    <div id="products">
        <div style="float: right; width: 350px; border: 1px solid #ccc; padding: 1em;">
            <strong>Server response:</strong>
            <ul id="response">
            </ul>
        </div>
        <div data-productid="653" class="rateit"></div>
    </div>

    <asp:Label ID="lblRating" runat="server" Text=""></asp:Label>
    <br />
    What was the best aspect of your experience?
    <br />
    <asp:TextBox ID="txtBest" TextMode="multiline" runat="server" Height="105px" Width="301px"></asp:TextBox>
    <br />
    What was the worst aspect of your experience?
    <br />
    <asp:TextBox ID="txtWorse" TextMode="multiline" runat="server" Height="105px" Width="301px"></asp:TextBox>
    <br />
    Do you have any suggestions?
    <br />
    <asp:TextBox ID="txtSuggestions" TextMode="multiline" runat="server" Height="105px" Width="301px"></asp:TextBox>
    <br />
    Would you recommend this service to your friend or family?
    <br />
    <asp:RadioButtonList ID="rblRecommend" runat="server">
        <asp:ListItem Value="N">No</asp:ListItem>
        <asp:ListItem Value="Y">Yes</asp:ListItem>
    </asp:RadioButtonList>
    <p></p>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    <asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>
    <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click1" />
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>

ASP.NET C#:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    ...
    try
    {
        connection.Open();

        string cmdText = "INSERT INTO feedback (stars, best, worse, suggestions, recommend) VALUES (?stars, ?best, ?worse, ?suggestions, ?recommend);";
        MySqlCommand cmd = new MySqlCommand(cmdText, connection);

        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("?stars", MySqlDbType.VarChar).Value = **lblRating.Text**;
        cmd.Parameters.Add("?best", MySqlDbType.VarChar).Value = txtBest.Text;
        cmd.Parameters.Add("?worse", MySqlDbType.VarChar).Value = txtWorse.Text;
        cmd.Parameters.Add("?suggestions", MySqlDbType.VarChar).Value = txtSuggestions.Text;
        cmd.Parameters.Add("?recommend", MySqlDbType.VarChar).Value = rblRecommend.SelectedValue;

        int result = cmd.ExecuteNonQuery();
        lblError.Text = "Data Saved";
    }
    ...

EDIT: This JavaScript enables a user to select a rating and the output gets displayed in lblRating :

     <script type ="text/javascript">
         //we bind only to the rateit controls within the products div
         $('#products .rateit').bind('rated reset', function (e) {
             var ri = $(this);

             //if the use pressed reset, it will get value: 0 (to be compatible with the HTML range control), we could check if e.type == 'reset', and then set the value to  null .
             var value = ri.rateit('value');
             var productID = ri.data('productid'); // if the product id was in some hidden field: ri.closest('li').find('input[name="productid"]').val()

             //maybe we want to disable voting?
             ri.rateit('readonly', true);

             $.ajax({
                 url: 'rateit.aspx', //your server side script
                 data: { id: productID, value: value }, //our data
                 type: 'POST',
                 success: function (data) {
                     $('#response').append('<li>' + data + '</li>');
                     $('#lblRating').append(data);
                 },
                 error: function (jxhr, msg, err) {
                     $('#response').append('<li style="color:red">' + msg + '</li>');
                 }
             });
         });
     </script>

Why doesn't the following ASP.NET C# code output anything?

protected void Button2_Click1(object sender, EventArgs e)
{
    Label1.Text = lblRating.Text;
}

try with below changes to your ajax call. Also Use [WebMethod()] and a static method.

$.ajax({
   url: 'rateit.aspx',
   type: "POST",
   contentType: 'application/json',
   data: JSON.stringify({id: productID, value: value}),
   dataType: "json",
  }).success(function ()

The DOM manipulation using $('#lblRating').append(data); only happens client side, updating the contents of a span element. (You can check this using your browser's tools, like Chrome's Inspect Element - other browsers have a similar feature).

As you've only updated a 'label', when you postback using your button event, the value is lost. The reason that the TextBox values persist is because they are included in the Form's data.

So, to include the rating value, you could attempt something using ajax, or to be more consistent with the rest of your approach, you could put the rating value in a form field (not a label), eg another TextBox , or a HiddenField as shown below.

Add your control to the Form (if you want to see it, use a TextBox instead):

<form id="form1" runat="server">
    ...
    <asp:HiddenField ID="hidRating" runat="server" />
</form>

On the return of your ajax call, update the value attribute of that control to the rating selected [ref: jQuery attr ]

success: function (data) {
    $('#response').append('<li>' + data + '</li>');
    $('#hidRating').attr('value', value);
    },

Then, in your server-side submit event, this should be available to add the value to the parameter:

cmd.Parameters.Add("?stars", MySqlDbType.VarChar).Value = hidRating.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM