在 Razor 页面中,我尝试将发票数据保存到 SQL Server 表中
Sales
,但是当您按下“保存发票”按钮时,没有任何反应,甚至没有错误消息,并且数据未保存。
我检查了所有内容,没有发现任何错误。
这是我的
cshtml.cs
代码 - 请注意,有一个项目名称和客户名称的选择列表:
using AfterFix.Pages.Clients;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace AfterFix.Pages.Sales
{
public class NewSalesModel : PageModel
{
private readonly string _connectionString = "Data Source=DESKTOP-9CABSPL\\SQLEXPRESS;Initial Catalog=mystore;Integrated Security=True;MultipleActiveResultSets=true";
public class Invoice
{
// Define properties relevant to an invoice
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; } = DateTime.Now;
public string CustomerName { get; set; }
// Other properties as needed
}
// Fetch customers
public List<SelectListItem> CustomerList { get; set; } = new List<SelectListItem>();
public List<SelectListItem> Items { get; set; } = new List<SelectListItem>();
public Invoice invoice = new Invoice();
public string errorMessage = "";
public string SuccsesMessage = "";
public void OnGet()
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var query = "SELECT Id, Name FROM customers";
using (var command = new SqlCommand(query, connection))
{
var reader = command.ExecuteReader();
while (reader.Read())
{
var customerId = reader["Id"].ToString();
var customerName = reader["Name"].ToString();
CustomerList.Add(new SelectListItem
{
Value = customerId,
Text = customerName
});
}
}
// Fetch items
var itemQuery = "SELECT Id, ItemName FROM items"; // Adjust the query according to your database schema
using (var itemCommand = new SqlCommand(itemQuery, connection))
{
var itemReader = itemCommand.ExecuteReader();
while (itemReader.Read())
{
var itemId = itemReader["Id"].ToString();
var itemName = itemReader["ItemName"].ToString();
Items.Add(new SelectListItem
{
Value = itemId,
Text = itemName
});
}
}
}
}
public int SelectedCustomerId { get; set; }
//public int InvoiceId { get; set; } // For existing invoices (optional)
// public string InvoiceNumber { get; set; }
// public DateTime InvoiceDate { get; set; } = DateTime.Now; // Defaults to current date
// public int CustomerId { get; set; }
// public string CustomerName { get; set; }
public void OnPost()
{
invoice.InvoiceNumber = Request.Form["InvoiceNumber"];
// Parse InvoiceDate
if (!DateTime.TryParse(Request.Form["InvoiceDate"], out DateTime invoiceDate))
{
errorMessage = "";
return;
}
invoice.InvoiceDate = invoiceDate;
// Parse CustomerId
// Parse the CustomerName from the appropriate form field
string customerName = Request.Form["CustomerName"];
// Validate if the parsed value is not null or empty
if (string.IsNullOrEmpty(customerName))
{
errorMessage = "";
return;
}
// Assign the parsed CustomerName to invoice.CustomerName
invoice.CustomerName = customerName;
// Validation
if (string.IsNullOrEmpty(invoice.InvoiceNumber) ||
invoice.InvoiceDate == DateTime.MinValue ||
invoice.CustomerName == null)
{
errorMessage = "";
return;
}
// Save to database
try
{
string connectionString = "Server=DESKTOP-9CABSPL\\SQLEXPRESS;Database=mystore;Trusted_Connection=True;MultipleActiveResultSets=true";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "INSERT INTO sales (InvoiceNumber, InvoiceDate, CustomerName) VALUES (@InvoiceNumber, @InvoiceDate, @CustomerName);";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@InvoiceNumber", invoice.InvoiceNumber);
command.Parameters.AddWithValue("@InvoiceDate", invoice.InvoiceDate);
command.Parameters.AddWithValue("@CustomerName", invoice.CustomerName);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
// Handle other unexpected exceptions
// Handle the exception
errorMessage = "";
// Log the exception or handle it in another appropriate way
// Log the exception details
}
// Clear input fields and set success message
invoice.InvoiceNumber = "";
invoice.InvoiceDate = DateTime.Now;
invoice.CustomerName = "";
SuccessMessage = "";
Response.Redirect("/sales/Index");
}
}
}
这是
.cshtml
标记和代码:
@page
@model AfterFix.Pages.Sales.NewSalesModel
@{
ViewData["Title"] = "New Sales Invoice";
}
<h1>New Sales Invoice</h1>
<form method="post" id="invoiceForm">
<div class="form-group">
<label for="invoiceNumber">Invoice Number:</label>
<input type="text" id="invoiceNumber" name="InvoiceNumber" class="form-control" value="@Model.invoice.InvoiceNumber" />
</div>
<div class="form-group">
<label for="invoiceDate">Invoice Date:</label>
<input type="date" id="invoiceDate" name="InvoiceDate" class="form-control" value="@Model.invoice.InvoiceDate.ToString("yyyy-MM-dd")" />
</div>
<div class="form-group">
<label for="customerName">Customer:</label>
<select id="customerName" name="SelectedCustomerName" class="form-control " value="@Model.invoice.CustomerName" />
<option value="">Select Customer</option>
@foreach (var customer in Model.CustomerList)
{
<option value="@customer.Value">@customer.Text</option>
}
</select>
</div>
<table class="table" id="itemsTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="Items" class="form-control item" onchange="calculateTotal()">
<option value="">Select Item</option>
@foreach (var item in Model.Items)
{
<option value="@item.Value">@item.Text</option>
}
</select>
</td>
<td><input type="number" name="Quantities" class="form-control quantity" onchange="calculateTotal()" /></td>
<td><input type="number" name="Prices" class="form-control price" onchange="calculateTotal()" /></td>
<td><input type="number" name="TotalPrice" class="form-control total" readonly /></td>
<td><button type="button" class="btn btn-danger" onclick="deleteRow(this)">Delete</button></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-success" onclick="addRow()">Add Item</button>
<br />
<div class="form-group">
<label for="totalPrice">Total Price:</label>
<input type="number" id="totalPrice" name="TotalPrice" class="form-control" readonly />
</div>
<button type="submit" class="btn btn-primary">Save Invoice</button>
</form>
@section scripts {
<script>
function calculateTotal() {
var rows = document.querySelectorAll("#itemsTable tbody tr");
var total = 0;
rows.forEach(function (row) {
var quantity = parseFloat(row.querySelector(".quantity").value) || 0;
var price = parseFloat(row.querySelector(".price").value) || 0;
var totalPrice = quantity * price;
row.querySelector(".total").value = totalPrice.toFixed(2);
total += totalPrice;
});
document.getElementById("totalPrice").value = total.toFixed(2);
}
function deleteRow(btn) {
var row = btn.closest("tr");
row.parentNode.removeChild(row);
calculateTotal();
}
function addRow() {
var table = document.getElementById("itemsTable").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.rows.length);
newRow.innerHTML = `
<td><select name="Items" class="form-control item" onchange="calculateTotal()"><option value="">Select Item</option>@foreach (var item in Model.Items)
{
<option value="@item.Value">@item.Text</option>
}</select></td>
<td><input type="number" name="Quantities" class="form-control quantity" onchange="calculateTotal()" /></td>
<td><input type="number" name="Prices" class="form-control price" onchange="calculateTotal()" /></td>
<td><input type="number" name="TotalPrice" class="form-control total" readonly /></td>
<td><button type="button" class="btn btn-danger" onclick="deleteRow(this)">Delete</button></td>
`;
}
</script>
}
Request.Form["CustomerName"];
为 null,不返回任何内容。这样数据库操作就不会受到影响。
Request.Form
通过键获取值,键名称应与元素名称匹配。选择元素被命名为 SelectedCustomerName
而不是 customerName
:
<select id="customerName" name="SelectedCustomerName" class="form-control " value="@Model.invoice.CustomerName">
所以你需要将代码更改为:
string customerName = Request.Form["SelectedCustomerName"];