Моя форма «Создать форму» не использует метод OnPost.
Я потратил немало часов, пытаясь решить эту проблему. Хотя я новичок и понятия не имею, что происходит. Я попытался изучить это и в итоге надеялся, что публикация этого сообщения поможет мне получить ответы.
Я проверил, что, если errorMessage и SuccessMessage не пусты, сообщение распечатывается правильно. Но я не могу заставить это работать так, как должно. Форма просто обнуляется, и я не вижу разницы.
Заранее спасибо!
Value.cs:
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace TaxCalculator.Models
{
public class Value {
public int Id { get; set; } = 0;
[MaxLength(100)]
public string Name { get; set; } = "";
}
}
ЗначениеDto:
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace TaxCalculator.Models
{
public class ValueDto
{
[Required]
[MaxLength(100)]
public string Name { get; set; } = "";
}
}
Create.cshtml:
@page
@using Microsoft.EntityFrameworkCore.Metadata.Internal
@model TaxCalculator.Pages.Admin.Products.CreateModel
@{
}
New Value
@if (Model.errorMessage.Length > 0)
{
@Model.errorMessage
}
else if (Model.successMessage.Length > 0)
{
@Model.successMessage
}
Name
Submit
Cancel
Это файл Create.cshtml.cs:
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxCalculator.Models;
using TaxCalculator.Services;
namespace TaxCalculator.Pages.Admin.Values
{
public class CreateModel(ApplicationDbContext context) : PageModel
{
private readonly ApplicationDbContext context = context;
[BindProperty]
public ValueDto ValueDto { get; set; } = new ValueDto();
public void OnGet()
{
}
public string errorMessage = "";
public string successMessage = "";
public void OnPost()
{
if (!ModelState.IsValid)
{
errorMessage = "Please provide all the required fields";
return;
}
var credit = new Credit
{
Name = ValueDto.Name,
};
context.Values.Add(credit);
context.SaveChanges();
//clear the form
ValueDto.Name = "";
ModelState.Clear();
successMessage = "Credit created successfully";
Response.Redirect("/Admin/Products/Index");
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/788 ... n-creation