本文介绍了用户输入的服务器端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Web应用程序中有一个表,用户可以从中下单。下表显示了可用的数量,我们需要让用户输入他们需要的数量,如下所示
当点击Order按钮时,我想验证用户输入的数量是否大于可用数量。每次单击Order按钮时,它都会调用控制器来检索数据并对照数量进行检查。该视图如下所示
@model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
@{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<div class="col-md-9">
<table class="table">
<thead>
<tr>
<th>
Strain ID
</th>
<th>
Strain Name
</th>
<th>
Quantity Avail
</th>
<th>
Room Number
</th>
<th>
Quantity Required
</th>
<th></th>
</tr>
</thead>
<tbody>
@{var custID = Model.CustomerData; }
@foreach (var item in Model.Inventorys)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
@Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
@Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
<form method="post"
asp-controller="Inventories"
asp-action="OrderItem">
<row>
<column>
<input type="text" id="quantityReq" name="quantityReq" value=@item.QuantityReq size="4" />
<input type="hidden" id="customerID" name="customerID" value="@custID.CustomerId" />
<input type="hidden" id="invetoryID" name="invetoryID" value="@item.InventoryId" />
<button type="submit" style="border: none; background-color: transparent; color: #1a0dab "><u>Order</u></button>
</column>
</row>
</form>
</td>
</tr>
}
</tbody>
</table>
@{
var prevDisabled = !Model.Inventorys.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Inventorys.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-pageNumber="@(Model.Inventorys.PageIndex - 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @prevDisabled"> Previous </a>
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-pageNumber="@(Model.Inventorys.PageIndex + 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @nextDisabled"> Next </a>
</div>
</div>
而我在单击按钮时调用的控制器操作是
public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (quantityReq <= intData.QuantityAvailable)
{
MouseOrder mo = new MouseOrder();
mo.CustomerId = (int)customerID;
mo.OrderDate = DateTime.Now;
mo.SamaccountName = "dvella";
_context.Add(mo);
await _context.SaveChangesAsync();
InventoryOrder io = new InventoryOrder();
io.OrderId = mo.MouseOrderId;
io.OrderQuantity = quantityReq;
io.InventoryId = (int)invetoryID;
_context.Add(io);
await _context.SaveChangesAsync();
intData.QuantityAvailable = intData.QuantityAvailable - quantityReq;
_context.Update(intData);
await _context.SaveChangesAsync();
}
else if (quantityReq > intData.QuantityAvailable){
}
return RedirectToAction("Index", "Inventories", new { id = customerID });
}
控制器中的获取操作如下所示
// GET: Inventories
public async Task<IActionResult> Index(int? id, string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
if (id == null)
{
return NotFound();
}
ViewData["StockParam"] = String.IsNullOrEmpty(sortOrder) ? "st_desc" : "";
ViewData["CurrentFilter"] = searchString;
ViewData["CurrentSort"] = sortOrder;
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
var inventories_data = from s in _context.Inventories
where s.QuantityAvailable >0
select s;
if (!String.IsNullOrEmpty(searchString))
{
inventories_data = inventories_data.Where(s => s.StrainCode.Contains(searchString));
}
switch (sortOrder)
{
case "st_desc":
inventories_data = inventories_data.OrderByDescending(s => s.StrainCode);
break;
default:
inventories_data = inventories_data.OrderBy(s => s.StrainCode);
break;
}
int pageSize = 15;
Customer custData = await _context.Customers.FindAsync(id);
var inventories = await PaginatedList<Inventory>.CreateAsync(inventories_data.AsNoTracking(), pageNumber ?? 1, pageSize);
var model = new CustomerInventoryCollectionDataModel
{
CustomerData = custData,
Inventorys = inventories
};
return View(model);
}
模型类类似
public class CustomerInventoryCollectionDataModel
{
public Customer CustomerData { get; set; }
public PaginatedList<Inventory> Inventorys { get; set; }
}
库存分类类似的位置
public partial class Inventory
{
public string StrainId { get; set; }
public string StrainName { get; set; }
public int QuantityAvailable { get; set; }
public string RoomNumber { get; set; }
public int InventoryId { get; set; }
[NotMapped]
public int? QuantityReq { get; set; }
}
我是第一次使用.NET Core和EF开发Web应用程序,并且有点坚持这样做。请建议我如何处理这里的验证。我在这里并不是特别说明应该在哪里显示验证消息,而是一种通知用户输入正确号码的方法。感谢大家的帮助
*编辑*
我看到的错误如下当我输入的数量少于或超过可用数量时,它不会执行任何操作,在DevTool中我看到类似屏幕截图的错误
Uncaught SyntaxError: Function statements require a function name
在按下"立即购买"按钮之前,URL类似于我按下https://localhost:44330/Inventories/Index/460#
后的任何URLhttps://localhost:44330/Inventories/Index/460#
我无法进行更多的故障排除,有点卡在这里
推荐答案
试试这个。由于它使用的是AJAX,我删除了一个表单和一个提交按钮
@model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
@{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<table>
<thead>
<tr>
<th style="padding-right:1em">
Strain ID
</th>
<th style="padding-right:1em">
Strain Name
</th>
<th style="padding-right:1em">
Room
</th>
<th style="padding-right:1em">
Quantity Avail
</th>
<th>
Quantity Required
</th>
<tbody>
@foreach(var item in Model.Inventorys)
{
<tr>
<td />
<td />
<td />
<td />
<td style="padding-right:1em">
<input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="@("errorMessage"+@item.InventoryId)" readonly />
</td>
</tr>
<tr style="padding-left:2em">
<td>
@Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
@Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
@Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
<row>
<column>
<input type="text" style="text-align:right;padding-right:1em" id="@("quantityReq"+@item.InventoryId)" name="quantityReq" value="@item.QuantityReq" />
</column>
<column>
<input type="hidden" id="@("customer"+@item.InventoryId)" name="customerID" value="@Model.CustomerData.Id" />
<input type="hidden" id="@("inventory"+@item.InventoryId)" name="invetoryID" value="@item.InventoryId" />
<a href="#" class="buyNow" data-id="@item.InventoryId"> Buy now</a>
</row>
</td>
</tr>
}
</tbody>
</table>
@section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".buyNow", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var id=$(this).data("id");
onBuyNow(id);
}));
function onBuyNow(id) {
$("#errorMessage" + id).val("");
var quantityReq = $("#quantityReq"+id).val();
var customerId = $("#customer"+id).val();
var data = {
customerId: customerId,
quantityReq: quantityReq,
inventoryId: id
};
$.ajax({
url: '@Url.Action("OrderItem", "Inventories")',
dataType: 'json',
type: 'POST',
data: data,
success: function (result) {
if (result.status !== "Ok") {
$("#errorMessage" + result.inventoryId).val("available only " + result.available);
}
else {
var url = '@Url.Action("Index", "Inventories")';
url=url++"?id="+customerId;
alert("url: " + url);
window.location.href = url;
};
error: function (error) {
alert("error");
}
});
};
}
});
</script>
}
操作
public async Task<ActionResult> OrderItem(int? customerID, int? inventoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(inventoryID);
if (quantityReq <= intData.QuantityAvailable)
{
... your code
}
else if (quantityReq > intData.QuantityAvailable){
return Ok( new { status = "NotAvailable", inventoryId=inventoryId, available = intData.QuantityAvailable} );
}
return Ok(new { status="Ok" } );
}
布局的正文部分的底部应
<script src="~/lib/jquery/dist/jquery.min.js"></script>
@await RenderSectionAsync("Scripts", required: false)
这篇关于用户输入的服务器端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!