【发布时间】:2020-12-09 18:23:09
【问题描述】:
我这里有两种情况。第一种发生在我路由到的页面存在时,另一种发生在页面不存在时。有点奇怪。
我尝试在 asp.net core 中向我的数据库添加一个对象,但是当我单击页面上的订单按钮时,它会将我重定向到应用程序的索引页面(没什么大不了的),但我的问题是我在POST请求中发送的对象没有添加到数据库中。
另一方面,如果页面不存在,则将对象添加到数据库中(没问题),但我收到内部服务器错误,提示在用于搜索的文件夹中找不到“索引” page.我的问题是我怎样才能仍然将对象添加到我的数据库并仍然路由到我想要路由到的页面(例如感谢您的购买页面)。
我现在将提供我使用的控制器的代码和端点代码:
端点:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
控制器:
[Route("api/shopping")]
[ApiController]
public class SendItemsController : Controller
{
private AppDbContext _db;
public SendItemsController(AppDbContext db)
{
_db = db;
}
[HttpPost]
[Consumes("application/json")]
public async Task<IActionResult> Save([FromBody] ShoppingCart s)
{
await _db.ShoppingCarts.AddAsync(s);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
public IActionResult Index()
{
return View();
}
}
<form method="post" asp-controller="SendItems" asp-action="Save">
<div class="form-group row">
<div class="col-4">
<label id="clientName"></label>
</div>
<div class="col-6">
<input id="inputName" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientAddress"></label>
</div>
<div class="col-6">
<input id="inputAddress" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientMail"></label>
</div>
<div class="col-6">
<input id="inputMail" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-4">
<button class="btn btn-primary " id="orderB">ORDER</button>
</div>
</div>
</form>
这是我在购物车页面上使用的 javascript:
var orderB = document.getElementById("orderB");
orderB.addEventListener("click", function () {
var inputName = document.getElementById("inputName").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputMail = document.getElementById("inputMail").value;
var auxArray = [];
for (var i = 0; i < productsAux.length; i++) {
if (productsAux[i]!="") {
auxArray[i-1] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu) };
}
}
var shoppingCart = {
productList: auxArray,
clientName: inputName,
clientAddress: inputAddress,
clientMail: inputMail
};
$.ajax({
type: "POST",
data: JSON.stringify(shoppingCart),
url: "api/Shopping",
contentType: "application/json;charset=utf-8",
})
})
【问题讨论】:
-
如果它在此代码中进行重定向,则该对象将被保存。听起来您需要附加一个调试器并验证此方法是否被命中。
-
@mason 第一次没有被点击,但是如果我进入购物车页面并再次点击按钮,它就会被点击。
标签: c# asp.net asp.net-core asp.net-mvc-4 asp.net-web-api