【问题标题】:Show Validation error on the different View from the action is not working在来自操作的不同视图上显示验证错误不起作用
【发布时间】:2021-12-15 21:02:29
【问题描述】:

我正在构建我的第一个 .NET Core MVC 应用程序并使用实体框架。一个按钮调用 AddtoOrder 页面,它接收来自上一页的一组参数,AddtoOrder 页面是允许用户输入他们想要订购的数量的地方。模型类如下所示

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

Inventory 是另一个类

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 &gt; 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 页面上。如何处理验证错误!

【问题讨论】:

    标签: javascript jquery ajax asp.net-core asp.net-ajax


    【解决方案1】:

    您可以使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      相关资源
      最近更新 更多