在操作的不同视图上显示验证错误不起作用

Show Validation error on the different View from the action is not working

我正在构建我的第一个 .NET Core MVC 应用程序并使用 Entity Framework。调用 AddtoOrder 页面的按钮从上一页接收一组参数,AddtoOrder 页面允许用户输入他们想要订购的数量。型号class如下

public class Item
{
    public int CustomId { get; set; }
    public Inventory Inventory { get; set; }
}

Inventory 是另一个 class

public partial class Inventory
    {
        public string Name { get; set; }
        public int QuantityAvailable { get; set; }
        public string RoomNumber { get; set; }
        public int InventoryId { get; set; }

        [NotMapped]
        public int? QuantityReq { get; set; }
    }

此处的 AddtoOrder 视图 QuantityReq 是用户将输入所有从数据库中检索到的其他字段的唯一字段。

@model JAXSurplusMouseApp.Models.Item

@{
    ViewData["Title"] = "Edit";
}

<h4>Add to Order</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="AddtoOrder">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
           <div class="form-group">
                <label asp-for="@Model.Inventory.Name" class="control-label"></label>
                <input asp-for="@Model.Inventory.Name" class="form-control" readonly />
            </div>
            <div class="form-group">
                <label asp-for="@Model.Inventory.QuantityAvailable" class="control-label"></label>
                <input asp-for="@Model.Inventory.QuantityAvailable" class="form-control" readonly />
            </div>
            <div class="form-group">
                <label asp-for="@Model.Inventory.RoomNumber" class="control-label"></label>
                <input asp-for="@Model.Inventory.RoomNumber" class="form-control" readonly />
            </div>
        </form>
        <form method="post"
              asp-controller="Inventories"
              asp-action="OrderItem">
            <label class="control-label">Quantity Required</label>
            <input type="text" id="quantityReq" name="quantityReq" value=@Model.Inventory.QuantityReq />
            @Html.ValidationSummary(false, "", new { @class = "error" })
            <input type="hidden" id="customerID" name="customerID" value="@Model.CustomId" />
            <input type="hidden" id="invetoryID" name="invetoryID" value="@Model.Inventory.InventoryId" />
            <button type="submit"><u>Order</u></button>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

所以我需要根据数据库中的值验证用户输入的值,因此在控制器中,我比较如下所示的值,如果用户输入的数量大于数据库中可用的数量 else if (quantityReq > intData.QuantityAvailable)OrderItem

// Action to launch the AddtoOrder page 
public async Task<IActionResult> AddtoOrder(int? inventoryID, int? custID)
 {
    if (inventoryID == null || custID == null)
    {
        return NotFound();
    }
    Customer custData = await _context.Customers.FindAsync(custID);
    var inventories = await _context.Inventories.FindAsync(inventoryID);
    var model = new Item
    {
        CustomId = (int)custID,
        Inventory = inventories
    };
    return View(model);
}

//Action athat allows the users to submit the order
 public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
    {
        if (customerID == null || invetoryID == null)
        {
            return NotFound();
        }
        Customer custData = await _context.Customers.FindAsync(customerID);
        var intData = await _context.Inventories.FindAsync(invetoryID);

            if (quantityReq <= intData.QuantityAvailable && quantityReq > 0)
            {
                InventoryOrder io = new InventoryOrder();
                io.OrderQuantity = quantityReq;
                io.InventoryId = (int)invetoryID;
                _context.Add(io);
                await _context.SaveChangesAsync();

                intData.QuantityAvailable = intData.QuantityAvailable - quantityReq;
                _context.Update(intData);
                await _context.SaveChangesAsync();  
                return RedirectToAction("Index", "Inventories", new { id = customerID });              
            }

            else if (quantityReq > intData.QuantityAvailable){
                 ModelState.AddModelError("QuantityReq", "Quantity entered more than Quantity Available");
            return RedirectToAction("AddtoOrder", "Inventories", new { inventoryID = invetoryID, custID = customerID });              
            }
        }

由于我要从操作返回到不同的视图,验证错误不会显示在 OrderItem 操作的 AddtoOrder 页面上。我该如何处理验证错误!

您可以使用 TempData 存储验证失败标志,如下所示:

[HttpGet]
public IActionResult AddtoOrder(int? inventoryID, int? custID)
{
    if (inventoryID == null || custID == null)
    {
        return NotFound();
    }
    Customer custData = await _context.Customers.FindAsync(custID);
    var inventories = await _context.Inventories.FindAsync(inventoryID);
    var model = new Item
    {
        CustomId = (int)custID,
        Inventory = inventories
    }; 
     //add the following code to judge if validation fail or not...
    if(TempData["Error"]!=null)
    {
        ModelState.AddModelError("Inventory.QuantityReq", "Quantity entered more than Quantity Available");
    }
    return View(model);
}
[HttpPost]
public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
{
    //...
    else if (quantityReq > intData.QuantityAvailable)
    {
        TempData["Error"] = "Validation fail";   //add this...
        return RedirectToAction("AddtoOrder", "Inventories", new { inventoryID = invetoryID, custID = customerID });
    }
    return View();
}