【问题标题】:ASP.Net Core MVC save to database method is not fired for the first time.After I go back and fire it again it works perfectlyASP.Net Core MVC 保存到数据库的方法第一次没有被触发。在我回去再次触发它之后它工作得很好
【发布时间】:2020-12-18 07:28:21
【问题描述】:

我有一个应用程序,我在其中将一些 JSON 数据发布到我的服务器,然后创建一个稍后将添加到数据库的对象。这是通过我的“SendItemsController”中的“Save”方法完成的:

 [Route("SendItems/Save")]
    [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 RedirectToAction("Index");
        }
        [HttpGet("~/ThankYou/Index")]
        public IActionResult Index()
        {
            return View();
        }
        
    }

将对象添加到数据库后,我尝试将客户端重定向到“ThankYou”页面。
当我在“购物车”页面上按下订单按钮首次启动时,它会将客户重定向到“ThankYou”页面而不触发“Save”方法,但如果我从“ThankYou”页面返回“Cart”页面并再次点击按钮,该方法被触发,对象被添加到数据库中,客户端被重定向到“ThankYou”页面,就像它应该做的那样。我的问题是我应该对我的代码进行什么更改才能实现它从第一次开始,而不是在返回并再次点击订单按钮之后。
我将提供我编写的代码。

这是我用来形成我的 JSON 对象然后将其发布到我的服务器的 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: "senditems/save",
                contentType: "application/json;charset=utf-8",
                
            })
            
        })
      

这是我用来收集客户姓名、地址和电子邮件的表单的 html:

    <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" asp-controller="SendItems" action="Save">ORDER</button>
        </div>
    </div>
</form>

【问题讨论】:

  • 看起来 ORDER 按钮和 JavaScript 一样会提交。有点猜猜哪个是第一个。或者哪一个成功了。
  • 那我该怎么办?
  • 尝试其中一种。不知道为什么在这里需要 JavaScript。
  • 如果你确实想使用 JS,那就把按钮变小:添加 "type="button" 并删除 Action 和 Controller 属性。
  • @HenkHolterman 我用它来构建我的 JSON 对象。在我的购物车页面中,我没有 JSON 数据的输入。该项目是一个服装网站,我在页面周围传递数据本地存储。当客户决定购买东西时,他们会转到购物车页面并在那里填写表格。在我的 javascript 中,我构建了那个 JSON,当客户点击“ORDER”时,名称、地址、电子邮件和产品形成一个 C# 对象然后将其添加到数据库中。

标签: asp.net routes asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

首先,我不确定你是否提供了整个 ajax,因为 ajax 请求的操作不会让你在后端重定向。你只能在你的 ajax 函数中重定向它。

其次,你已经添加了onclick事件,不需要添加asp-controller tag helper,它会呈现错误的formaction。

第三,项目i以0开头但auxArray的索引以-1开头,产品数组可能无法成功传递到后端。

最后,ajax url 应该是:/senditems/save

这是一个如下所示的工作演示:

型号:

public class ShoppingCart
{
    public string clientName { get; set; }
    public string clientAddress { get; set; }
    public string clientMail { get; set; }
    public List<Product> productList { get; set; }
}
public class Product
{
    public string productName { get; set; }
    public int productPrice { get; set; }
    public int quantity { get; set; }
}

查看:

<form>
    //....  
    <div class="form-group row">
        <div class="col-3 offset-4">
            <button class="btn btn-primary" id="orderB" type="button">ORDER</button>
        </div>
    </div>
</form>
@section Scripts
{
    <script>
        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 < 1; i++) {
                auxArray[i] = { "productName": "aaaa", "productPrice": 34, "quantity": 3 };
            }
            var shoppingCart = {
                productList: auxArray,
                clientName: inputName,
                clientAddress: inputAddress,
                clientMail: inputMail
            };
            $.ajax({
                type: "POST",
                data: JSON.stringify(shoppingCart),
                url: "/senditems/save",  //add `/`
                contentType: "application/json;charset=utf-8",
                success: function (res) {
                    window.location.href = res; //redirect like this
                }
            })

        })
    </script>
}

控制器:

[Route("SendItems/Save")]
[ApiController]
public class SendItemsController : Controller
{
    [HttpPost]
    [Consumes("application/json")]
    public async Task<IActionResult> Save([FromBody] ShoppingCart s)
    {
        return Json("YourRedirectUrl");
    }
}

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多