I want to put the comment for every picture.Maybe can use component Input or other.Can show for me in code.

MIPAKTEH_1 365 Reputation points
2024-09-01T08:40:51.49+00:00
@page "/"
@using Microsoft.EntityFrameworkCore
@inject ICommentService CommentService
@rendermode @(new InteractiveServerRenderMode(prerender: false))

<h1 style="color: blue;">Letak Product Anda</h1>

<p> </p>

@for (int i = 0; i < images.Count; i++)
{
    string tempTitle = images[i].Title;
    int buttonNumber = i;
    bool Cancomment = images[i].CanComment;
    var model = images[i];
    <div style="float:left; text-align:center; margin:10px;">
        <img src=@($"/Images/{images[i].Image}")
             style="width:200px;height:200px; cursor:pointer;border:dashed 1px #333;" />
        <div>@tempTitle</div>
        <div style="width:200px;height:50px;">
            @if (Cancomment)
            {
                <input style="width:60%" @bind="@model.Comment" />
                <button class="btn-primary small" @onclick="@(e => SubmitComment(e,buttonNumber))">Comment</button>
            }
        </div>
    </div>
}

@code {
    public class ImageComment
    {
        public int Id { get; set; }

        public string Title { get; set; } = string.Empty;
        public string Comment { get; set; } = string.Empty;
    }

    public class MyViewModel

    {
        public string Image { get; set; } = string.Empty;
        public string Title { get; set; } = string.Empty;
        public string Page { get; set; } = string.Empty;
        public string Comment { get; set; } = string.Empty;
        public bool CanComment { get; set; }

    }

    public class MyContext : DbContext
    {
        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        {
        }
        public DbSet<ImageComment> ImageComments { get; set; }

        public MyContext(DbSet<ImageComment> imageComments)
        {
            ImageComments = imageComments;
        }
    }

    public interface ICommentService
    {
        Task AddCommentAsync(ImageComment comment);
        List<ImageComment> GetComments();
    }

    public class CommentService : ICommentService
    {
        private readonly MyContext _context;
        public CommentService(MyContext context) => _context = context;
        public async Task AddCommentAsync(ImageComment comment)
        {
            _context.ImageComments.Add(comment);
            await _context.SaveChangesAsync();
        }
        public List<ImageComment> GetComments() => _context.ImageComments.ToList();
    }

    private readonly List<MyViewModel> images = new List<MyViewModel>()
    {
        new MyViewModel() { Image = "", Title = "Title 1", Page = "/PageA", CanComment = true },
        new MyViewModel() { Image = "", Title = "Title 2", Page = "/PageB", CanComment = true }
    };


    private void SubmitComment(MouseEventArgs e, int buttonNumber)
    {

        var comment = new ImageComment
            {
                Title = images[buttonNumber].Title,
                Comment = images[buttonNumber].Comment
            };

        CommentService.AddCommentAsync(comment);


    }
}
=========================================================================================
appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=xxxxxxx;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
  }
}

=========================================================================================
Program.cs


            NHibernateProfilerBootstrapper.PreStart();
using Bis_4.Components;
using Microsoft.EntityFrameworkCore;
using static Bis_4.Components.Pages.Home;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();


var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddScoped<ICommentService, CommentService>();


app.Run();

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,584 questions
{count} votes

Accepted answer
  1. Ping Ni-MSFT 4,335 Reputation points Microsoft Vendor
    2024-09-02T04:44:41.76+00:00

    Hi MIPAKTEH_1

    Please be sure you have Installed the

    Microsoft.EntityFrameworkCore.Design,Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore package.

    And the registration of the DbContext should be placed in the following location in Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    builder.Services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
    builder.Services.AddScoped<ICommentService, CommentService>();
    var app = builder.Build();
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseAntiforgery();
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();
    app.Run();
    

    Besides, I suggest you move the model design and interface to the separate file, cause the name of the CommentService class will conflict with the variable name you set here @inject ICommentService CommentService. If you do not want to move them, just change the variable name like below:

    @inject ICommentService _commentService
    @code{
    private void SubmitComment(MouseEventArgs e, int buttonNumber) 
    { 
        var comment = new ImageComment { Title = images[buttonNumber].Title, Comment = images[buttonNumber].Comment }; 
        _commentService.AddCommentAsync(comment);   //change here...
     }
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.