重定向后,ASP.NET Core MVC数据库不会添加对象

问题描述

在这里有2种情况。第一种情况发生在我要路由到的页面存在时,另一种情况发生在该页面不存在时。

我尝试在asp.net核心中向数据库添加一个对象,但是当我单击页面上的订购按钮时,它会将我重定向到应用程序的索引页面(没什么大不了的,可以解决),但是我的问题是我在POST请求中发送的对象没有添加数据库中。

另一方面,如果该页面不存在,则将该对象添加数据库中(没问题),但出现内部服务器错误提示在用于搜索文件夹的文件夹中找不到“索引”我的问题是我如何仍可以将对象添加数据库中并仍然路由到我要路由到的页面(例如,感谢您购买页面)。

我现在将提供所用控制器的代码和端点代码

端点:

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",})
        })

解决方法

RedirectToPage用于Razor Page,虽然这是一个MVC项目,但我认为您需要使用RedirectToAction

当我单击页面上的订购按钮时,它会将我重定向到应用程序的索引页面

因此,您想通过单击订单按钮来触发Save中的SendItemsController操作吗?请求是什么样的,URL对吗?也许您可以向我们展示客户端代码。

我做了一个简单的演示,并与邮递员进行了测试,您可以参考。

[HttpPost]
[Consumes("application/json")]
public async Task<IActionResult> Save([FromBody] ShoppingCart s)
{
    await _db.ShoppingCarts.AddAsync(s);
    await _db.SaveChangesAsync();
    return RedirectToAction("Thanks");
}

[HttpGet("Thanks")]
public IActionResult Thanks()
{
    return View();
}

enter image description here

更新

@section scripts{
    <script>
        var orderB = document.getElementById("orderB");
        orderB.addEventListener("click",function (e) {
            e.preventDefault();
            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",url: "/api/Shopping",contentType: "application/json;charset=utf-8",data: JSON.stringify(shoppingCart),})
        })
    </script>
}