首页 > 解决方案 > 根据 DB 值验证用户输入

问题描述

我正在构建我的第一个 .NET Core MVC 应用程序并使用实体框架。我有一个编辑页面,允许用户输入他们想要订购的数量。模型类如下

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

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

数据库中QuantityReq不存在,所以我将它们添加为NotMapped. 所以我有一个视图名称AddtoOrder在项目上,比如

@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 />
            <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");}
}

控制器操作如下所示,如果用户输入的数量超过了可用的数量,则下订单并导航回另一个页面。但是,如果用户在所需数量中输入的数字大于可用数量,那么我需要在他们输入无效数量的同一页面中发布错误消息

// 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){
                 How to redirect to the same page back with the  validation error                 
            }
        }

标签: javascriptjqueryajaxasp.net-coreasp.net-ajax

解决方案


首先,您应该添加@Html.ValidationSummary(false, "", new { @class = "error" })到您的表单中。另外,我建议您使用HTML Helpers

这是一个简单的表单示例:

    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name)
        @Html.LabelFor(m => m.Age)
        @Html.TextBoxFor(m => m.Age)
        <input type="submit" value="Submit"/>
        @Html.ValidationSummary(false, "", new { @class = "error" })
    }

然后您可以自定义验证您的模型并将错误发送到 View:

// Validation logic
else if (quantityReq > intData.QuantityAvailable) 
{
    ModelState.AddModelError("QuantityReq", "QuantityReq more than QuantityAvailable");
    return View();
}

推荐阅读