【发布时间】:2019-05-23 00:04:16
【问题描述】:
我学习 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 中一切正常。那为什么不呢?有什么问题?
【问题讨论】:
标签: c# jquery asp.net ajax webforms