簡體   English   中英

根據 DB 值驗證用戶輸入

[英]Validate user input against the DB value

我正在構建我的第一個 .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 所以我對這個項目有一個看法

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

控制器操作如下所示,如果用戶輸入的數量大於可用數量,則下訂單並導航回其他頁面。 但是,如果用戶在所需數量中輸入的數字大於可用數量,那么我需要在他們輸入的數量無效的同一頁面中發布錯誤消息

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

首先,您應該將@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" })
    }

然后您可以自定義驗證您的模型並將錯誤發送到視圖:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM