Home > Software engineering >  Trying to add comments to database
Trying to add comments to database

Time:04-11

Hi I'm a programmer at aspnetcore mvc and I'm trying to add comments to the database, In my project there are a certain amount of animals and I want each animal to be allowed to add comments according to its id.

My Comment Model:

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

My Animal Model:

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

My Controller&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);
    }

My View: @model PetShop.Data.Models.Comment

<form action="Indexx2" method="post">
<div >
            <label asp-for="Content" ></label>
            <input asp-for="Content"  />
            <span asp-validation-for="Content" ></span>
        </div>
<input type="submit" value="click me"/>

Validation:

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

}

CodePudding user response:

Before giving solution, I need note you that make property nullable if you use .NET 6. Otherwise it will fail for model validation.

For Example, change the property below:

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

To:

public string? PhotoUrl { get; set; } 

Here is a whole working demo:

View:

@model Comment

<form method="post">
    <select asp-items="ViewBag.Animal" asp-for="AnimalId"></select>
    <div >
        <label asp-for="Content" ></label>
        <input asp-for="Content"  />
        <span asp-validation-for="Content" ></span>
    </div>
    <input type="submit" value="click me"/>
</form>

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

Controller:

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