【问题标题】:My current insert statement is not working我当前的插入语句不起作用
【发布时间】:2020-12-18 07:21:30
【问题描述】:

我正在创建一个礼物表格供用户输入他们的价值观。然而,这些表格曾经可以工作,但突然,一天后,它就直接失效了。我不确定哪里出错了。请帮帮我。这是我的代码。我已经对其进行了审查,对我来说似乎很好。这个问题不断发生,我无法确定错误是什么。我认为这与日期有关。在数据库中,我将数据类型设置为 DATE。

CreateGift.cshtml

@*Create Gift Page*@
@model SignUp3.Models.Gift;
@section MoreScripts {
<script src="~/lib/moment/moment.min.js"></script>
<link href="~/lib/dtpicker/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet" />
<script src="~/lib/dtpicker/js/tempusdominus-bootstrap-4.min.js"></script>
<link href="~/lib/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<script src="~/lib/jquery-validate/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

    }
    <!DOCTYPE html>
    <head>
      <meta charset="UTF-8">
           <link rel="stylesheet" href="~/lib/styles/createform.css">
   </head>
   <body>
       <div class="center">
                <form id="createuser" asp-controller="Gift" asp-action="CreateGift"
                         method="post">
                  <h3>Create Gift</h3>
                  <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="description">Description:<span style="color:red;">*</span> </label>
            <div class="col-sm-5">
                <input asp-for="description" placeholder="Full Name" class="form-control" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="description" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="vouchercode">Voucher Code:<span style="color:red;">*</span> </label>
            <div class="col-sm-5">
                <input asp-for="vouchercode" placeholder="Voucher Code" class="form-control" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="vouchercode" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="amount">Voucher Amount:<span style="color:red;">*</span> </label>
            <div class="col-sm-5">
                <input asp-for="amount" placeholder="Amount" class="form-control" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="amount" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="quantity">Quantity:<span style="color:red;">*</span> </label>
            <div class="col-sm-5">
                <input asp-for="quantity" placeholder="Quantity" class="form-control" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="quantity" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="activation_date">Activation Date:<span style="color:red;">*</span></label>
            <div class="col-sm-5">
                <input asp-for="activation_date" asp-format="{0:yyyy-MM-dd}"
                       class="form-control" placeholder="YYYY-MM-DD" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="activation_date" class="text-danger"></span>

            </div>
        </div>

        <div class="form-group row">
            <label class="control-label col-sm-3" asp-for="expiry">Expiry Date:<span style="color:red;">*</span></label>
            <div class="col-sm-5">
                <input asp-for="expiry" asp-format="{0:yyyy-MM-dd}"
                       class="form-control" placeholder="YYYY-MM-DD" />
            </div>
            <div class="col-sm-3">
                <span asp-validation-for="expiry" class="text-danger"></span>

            </div>
        </div>
        <div class="form-group row">
            <div class="offset-sm-3 col-sm-6">
                <input type="submit" value="Submit" class="btn btn-primary" />
            </div>
        </div>

        @if (ViewData["Message"] != null)
        {
            <div class="form-group row">
                <div class="offset-sm-2 col-sm-6">
                    <div class="alert alert-@ViewData["MsgType"]">
                        @Html.Raw(ViewData["Message"])
                    </div>
                </div>
            </div>
        }
    </form>

</div>

GiftController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SignUp3.Models;

namespace SignUp3.Controllers
{
  public class GiftController : Controller
  {
    [Authorize]
    public IActionResult CreateGift()
    {
        return View();
    }


    [HttpPost]
    public IActionResult CreateGift(Gift gift)
    {
        // TODO: L09 Task 5 - Write secure code to insert Users into database
        if (!ModelState.IsValid)
        {
            ViewData["Message"] = "Invalid Input";
            ViewData["MsgType"] = "warning";
            return View("CreateGift");
        }
        else
        {

             
            string sql = @"INSERT INTO GiftVoucher (description,amount,vouchercode,quantity,activation_date,expiry)
            VALUES('{0}',{1},'{2}',{3},'{4}','{5}')";

            if (DBUtl.ExecSQL(sql, gift.description,gift.amount, gift.vouchercode,gift.quantity,gift.activation_date,gift.expiry) == 1)
            {
                TempData["Message"] = "Gift Sucessfully Added.";
                TempData["MsgType"] = "success";
                return RedirectToAction("ViewGift");
            }
            else
            {
                ViewData["Message"] = "Invalid";
                ViewData["MsgType"] = "danger";
                return View("CreateGift");
            }
        }
    }

【问题讨论】:

  • 很明显,您的问题出在DBUtl.ExecSQL(sql, gift.description,gift.amount, gift.vouchercode,gift.quantity,gift.activation_date,gift.expiry) == 1 这一行。从DBUtil.ExecSQL 返回什么?结果不是1是什么意思?可以返回哪些其他可能的值,它们的含义是什么?
  • 现在有什么问题?消息"Invalid Input" 没有显示?你调试检查 ModelState 了吗?
  • @mj1313 问题是,当我在表单中输入所有值后单击提交按钮时,它不会返回成功消息,而是进入“else { ViewData["Message"] = "无效"; ViewData["MsgType"] = "危险"; return View("CreateGift"); }"
  • @iwanttopassmyfyp 所以方法DBUtl.ExecSQL没有返回1,返回值是什么意思,你应该检查一下。
  • @mj1313 它返回值-1。为什么会这样?在正常的insert语句中,表格填写正确时,返回值应该是1。

标签: c# html asp.net asp.net-core-mvc


【解决方案1】:

从该字符串 17/12/2020 12:00:00 am 转换日期时转换失败。

您应该格式化插入参数以满足数据类型date

gift.expiry.ToString("yyyy-MM-dd")

【讨论】:

    【解决方案2】:

    这个看起来由于格式化而插入失败。我不知道DBUtl 在这里是什么,但是:它似乎就像您在使用string.Format 来构建SQL,这从根本上说是一个糟糕的主意,因为全部:

    • SQL 注入
    • i18n/l10n(日期/数字格式)
    • 处理字符串中的引号等
    • 查询计划缓存重用

    最终,执行这种查询的唯一正确方法是使用参数,而不是字符串替换。由于您在这里编写自己的 SQL,因此您可能会发现 Dapper(在 NuGet 上免费提供)是一个不错的选择:

    int ret = connection.Execute(@"
    INSERT INTO GiftVoucher (description,amount,vouchercode,quantity,activation_date,expiry)
    VALUES(@description,@amount,@vouchercode,@quantity,@activation_date,@expiry)", gift);
    

    Dapper 将在 gift 上寻找可能的成员,并添加 sql 中提到的成员。或者,匿名类型可能很有用:

    int ret = connection.Execute(@"
    INSERT INTO GiftVoucher (description,amount,vouchercode,quantity,activation_date,expiry)
    VALUES(@description,@amount,@vouchercode,@quantity,@activation_date,@expiry)",
        new { gift.description, /* etc */, gift.expiry });
    

    (当参数来自不同地方时,第二种方法很有用)

    【讨论】:

      猜你喜欢
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多