简体   繁体   English

根据 DB 值验证用户输入

[英]Validate user input against the DB value

I am build my first .NET Core MVC application and using the Entity Framework.我正在构建我的第一个 .NET Core MVC 应用程序并使用实体框架。 I have a edit page where users are allowed to enter the Quantity that they would like to order.我有一个编辑页面,允许用户输入他们想要订购的数量。 The model classes are like below模型类如下

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

and

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

The QuantityReq doesnot exists in the DB so I added them as NotMapped . QuantityReq不存在于数据库中,所以我将它们添加为NotMapped So I have a view on the 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");}
}

The Controller action is like below, if the user entering the quantity is more than the Quantity that is available then the order is placed and it navigates back to the other page.控制器操作如下所示,如果用户输入的数量大于可用数量,则下订单并导航回其他页面。 But if users enter a number in the Quantity required that is more than the Quantity Available then I need to post a error message in the same page that they have entered invalid quantity但是,如果用户在所需数量中输入的数字大于可用数量,那么我需要在他们输入的数量无效的同一页面中发布错误消息

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

first of all you should add @Html.ValidationSummary(false, "", new { @class = "error" }) to your form.首先,您应该将@Html.ValidationSummary(false, "", new { @class = "error" })到表单中。 Also, I would recommend you use HTML Helpers .另外,我建议您使用HTML Helpers

This is simple example of form:这是表单的简单示例:

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

And then you can custom validate your model and send error to View:然后您可以自定义验证您的模型并将错误发送到视图:

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