使用ajax向表和页面添加条目

时间:2018-12-23 10:59:59

标签: c# jquery asp.net ajax webforms

我学习javascript。得到了ajax请求。在mvc中一切正常。我决定尝试使用网络表单。尝试在页面上发布新条目时,请告诉我我做错了什么。这是我的代码。页面代码充当主视图:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tables.aspx.cs" Inherits="WebApplication1.Tables" %>

<!DOCTYPE html>
<script src="../../Scripts/jquery-1.8.0.min.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<html lang="en">
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>

<body>
    <div>
        <table id="tab" class="table table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Author</th>
                    <th>Price</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1408</td>
                    <td>Stiven King</td>
                    <td>500</td>
                </tr>
            </tbody>
        </table>
    </div>

    <form id="form1" runat="server">
        <asp:TextBox ID="txbName" runat="server"></asp:TextBox>
        <asp:TextBox ID="txbAuthor" runat="server"></asp:TextBox>
        <asp:TextBox ID="txbPrice" runat="server"></asp:TextBox>
        <input id="btnAdd" type="submit" value="Добавить" />
    </form>
</body>
</html>


<script>
    $('#btnAdd').on('click', function () {
        $.ajax({
            type: "POST",
            url: "Tables.aspx/AddBook",
            data: JSON.stringify({
                "Name": $('#txbName').val(),
                "Author": $('#txbAuthor').val(),
                "Price": $('#txbPrice').val()
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (MyDT) {
                $('#tab tbody').append(MyDT);
            },
            error: function (xhr) {
                alert(xhr.statusCode)
            }
        });
    });
</script>

Web方法代码,控制器:

[WebMethod]
        public static string AddBook(string Name, string Author, int Price)
        {
            db = new Context();
            string html = "";
            Book book = new Book() { Name = Name, Author = Author, Price = Price };
            db.Books.Add(book);
            db.SaveChanges();

            html = GetHTMLRow(book);
            return html;
        }

另一种获取html代码以进一步向页面添加条目的方法,类似于该条目将进入的部分视图:

public static string GetHTMLRow(Book book)
        {

            string htmlRow = $"<tr><td>{book.Name}</td><td>{book.Author}</td><td>{book.Price}</td></tr>";
            return htmlRow;
        }

我的代码可以正常工作,但是由于某种原因页面已重新启动。但是ajax请求是否应该在不触摸页面的情况下异步工作?在MVC中,一切正常。然后为什么不呢?有什么问题吗?

1 个答案:

答案 0 :(得分:1)

当您单击按钮时,它将提交表单(因为类型设置为“提交”)。将其更改为“按钮”

User