【问题标题】:ASP.NET Core MVC database does not add an object after redirectingASP.NET Core MVC 数据库重定向后不添加对象
【发布时间】: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


【解决方案1】:

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

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

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

我做了一个简单的demo,用postman测试过,大家可以参考一下。

[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();
}

更新:

@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>
}

【讨论】:

  • 我尝试按照你说的做,但现在我收到 415“此页面无法正常工作”
  • 我为我使用的表单添加了 html。另一方面,如果我有 public IActionResult Index() { return View(); } 方法,它会将对象添加到数据库中,但找不到索引页面。没有这个方法我获取我所说的 415。
  • 我是否必须创建另一个 MapControllerRoute,因为一切似乎都被路由到了 Index 方法。
  • 您的示例中的感谢页面在哪里?
  • 查看我的更新,感谢页面刚刚由Thanks 操作返回。如果您不知道如何添加视图,请右键单击Thanks 操作,选择Add View
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2021-03-25
  • 2019-07-09
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多