简体   繁体   中英

Validate user input against the DB value

I am build my first .NET Core MVC application and using the Entity Framework. 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 . 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. Also, I would recommend you use 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM