I try to put some comment for every Images.test to use input or maybe other component.All comments want to save it.II very newest , need help, the error at design time at line CommentService.AddCommentAsync(comment);

MIPAKTEH_1 365 Reputation points
2024-09-01T08:31:40.9566667+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. Tiny Wang-MSFT 2,721 Reputation points Microsoft Vendor
    2024-09-02T07:49:21.31+00:00

    Hi, I noticed that you have CommentService.AddCommentAsync(comment); which method should come from @inject ICommentService CommentService .

    If you put the codes below within the same component, you will have error like screenshot below.

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

    User's image

    I think you can change a name for CommentService like this: @inject ICommentService _commentService and _commentService.AddCommentAsync(comment);

    If the error I shared is different with yours, please share more about the error you are facing.


    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,
    Tiny Wang


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.