Hola, soy programador en aspnetcore mvc y estoy tratando de agregar comentarios a la base de datos. En mi proyecto hay una cierta cantidad de animales y quiero que cada animal pueda agregar comentarios de acuerdo con su identificación.
Mi modelo de comentario:
public Comment() { Animal = new Animal(); } [Key] public int CommentId { get; set; } public int AnimalId { get; set; } public string Content { get; set; } = null!; [ForeignKey("AnimalId")] [InverseProperty("Comments")] public virtual Animal Animal { get; set; } = null!;Mi modelo animal:
public Animal() { Comments = new HashSet<Comment>(); //Category = new Category(); } [Key] public int AnimalId { get; set; } [StringLength(50)] public string? Name { get; set; } [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] [DataType(DataType.Date)] [Display(Name = "Birth Date")] public DateTime? BirthDate { get; set; } public string? Description { get; set; } public int CategoryId { get; set; } [StringLength(200)] [Display(Name = "Portrait")] public string PhotoUrl { get; set; } = null!; [ForeignKey("CategoryId")] //[InverseProperty("Category")] public virtual Category Category { get; set; } = null!; //[InverseProperty("Animal")] public virtual ICollection<Comment> Comments { get; set; } }Mi controlador y acción (obtener, publicar):
public IActionResult Indexx() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Indexx([Bind("Content")] Comment comment) { if (ModelState.IsValid) { _context.Add(comment); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Indexx)); } return View(comment); }Mi vista: @model PetShop.Data.Models.Comment
<form action="Indexx2" method="post"> <div class="form-group"> <label asp-for="Content" class="control-label"></label> <input asp-for="Content" class="form-control" /> <span asp-validation-for="Content" class="text-danger"></span> </div> <input type="submit" value="click me"/>Validación:
@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}}
Antes de dar una solución, debo tener en cuenta que hace que la propiedad sea anulable si usa .NET 6 . De lo contrario, fallará para la validación del modelo.
Por ejemplo, cambie la propiedad a continuación:
public string PhotoUrl { get; set; } = null!;A:
public string? PhotoUrl { get; set; }Aquí hay una demostración de trabajo completa:
Vista:
@model Comment <form method="post"> <select asp-items="ViewBag.Animal" asp-for="AnimalId"></select> <div class="form-group"> <label asp-for="Content" class="control-label"></label> <input asp-for="Content" class="form-control" /> <span asp-validation-for="Content" class="text-danger"></span> </div> <input type="submit" value="click me"/> </form> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }Controlador:
public IActionResult Index() { ViewData["Animal"] = new SelectList(_context.Animal.ToList(), "AnimalId", "Name"); return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index([Bind("Content,AnimalId")] Comment comment) { if (ModelState.IsValid) { var animal = await _context.Animal.FindAsync(comment.AnimalId); comment.Animal = animal; _context.Add(comment); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(comment); }