На страницах Razor я пытаюсь сохранить данные счета-фактуры в таблице продаж sql, но когда вы нажимаете кнопку «Сохранить счет», ничего не происходит, даже не появляется сообщение об ошибке, и данные не сохраняются. Я все проверил и нашел ошибок нет
это мой код 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 CustomerList { get; set; } = new List();
public List Items { get; set; } = new List();
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 = "";
SuccsesMessage = "";
Response.Redirect("/sales/Index");
}
}
}
и этот cshtml-код
@page
@model AfterFix.Pages.Sales.NewSalesModel
@{
ViewData["Title"] = "New Sales Invoice";
}
New Sales Invoice
Invoice Number:
Invoice Date:
Customer:
Select Customer
@foreach (var customer in Model.CustomerList)
{
@customer.Text
}
Item
Quantity
Price
Total Price
Select Item
@foreach (var item in Model.Items)
{
@item.Text
}
Delete
Add Item
Total Price:
Save Invoice
@section scripts {
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 = `
Select Item@foreach (var item in Model.Items)
{
@item.Text
}
Delete
`;
}
}
Подробнее здесь: https://stackoverflow.com/questions/784 ... pages-net8