尝试向数据库添加评论

Trying to add comments to database

您好,我是 aspnetcore mvc 的一名程序员,我正在尝试向数据库添加评论, 在我的项目中有一定数量的动物,我希望每个动物都可以根据其id添加评论。

我的评论模型:

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!;

我的动物模型:

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; }
}

我的控制器&action(get,post):

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);
    }

我的看法: @模型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"/>

验证:

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}

在提供解决方案之前,我需要注意,如果您使用 .NET 6,请使 属性 可为空。否则模型验证将失败。

例如,更改下面的属性:

public string PhotoUrl { get; set; } = null!;

收件人:

public string? PhotoUrl { get; set; } 

这是一个完整的工作演示:

查看:

@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");}
}

控制器:

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);
}