【问题标题】:Validate user input against the DB value根据 DB 值验证用户输入
【发布时间】:2021-12-15 18:05:46
【问题描述】:

我正在构建我的第一个 .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 在 Item like

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

【问题讨论】:

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


    【解决方案1】:

    首先,您应该将@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();
    }
    

    【讨论】:

    • 谢谢。但是我在这里使用 EF 框架来获取其他字段的数据,只有 QuantityReq 这就是我标记为 NotMapped 所以我们可以允许用户输入它。我怎样才能让 HTML 助手只用于 QuantityReq 字段
    • 试试这个ModelState.AddModelError("", "QuantityReq more than QuantityAvailable"); 它将显示整个表单的常见错误。
    • 另外,您可以更改您的 HTML 并仅为此文件 @Html.TextBoxFor(x =&gt; x.QuantityReq) 添加 HTML 帮助程序。它将生成这样的 HTML &lt;input class="form-control" id="QuantityReq" name="QuantityReq" type="text" value="" /&gt;
    • 我遇到了一个问题。当我尝试输入更多数量来测试重定向不起作用。操作名称和视图名称不同,因此 return View(); 返回错误,指出视图 OrderItem 不存在。视图名称AddtoOrder 所以我尝试通过执行return RedirectToAction("AddtoOrder", "Inventories", new { inventoryID = invetoryID, custID = customerID }); 导航到视图,它返回到页面但我没有看到错误消息
    • 我更新了我的问题。实际上AddtoOrder 视图是在单击传递一些参数以填充字段的按钮时从上一页启动的。验证发生在不同的操作中,所以我如何从@ 导航回AddtoOrder 页面987654337@ 显示验证错误的操作
    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多