How to save the Comment and where to place, example some directory

MIPAKTEH_1 365 Reputation points
2024-08-17T11:08:23.0466667+00:00

@page "/PageBu"

@rendermode InteractiveServer

<h3>PageBu</h3>

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

<p> </p>

@for (int i = 0; i < images.Count; ++i)

{

string tempImageName = images[i].Page;

string tempTitle = images[i].Title;

int buttonNumber = 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 (images[i].CanComment)

        {

            <input style="width:60%" />

            <button class="btn-primary small" @onclick="@(e => ChangeStatus(e, buttonNumber))">comment</button>

        }

    </div>

</div>

}

@code {

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 bool CanComment { get; set; }

}

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 ChangeStatus(MouseEventArgs e, int buttonNumber)

{

    images[buttonNumber].CanComment = true;

}

}

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,595 questions
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,701 Reputation points Microsoft Vendor
    2024-08-20T03:14:11.4666667+00:00

    Hi @MIPAKTEH_1,

    Normally, we will store the comment data or else inside the database not directly inside the project's folder , since if you store it inside the folder , it's hard to read and show the comment if you want to see it.

    Then if you want to store it inside the database, you need set the database in somewhere, like VS's local sql server, it just used for testing, or sqllite database. If you want to host it inside the server, I suggest you could install the Microsoft sql database, or using some cloud service, like Azure sql database.

    For testing, I suggest you could follow below steps to create the database and using EF core to store the comment.e

    1.Install the Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore package

    2.Put the connection string inside the appsettings.json

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

    3.Create the dbcontext class and imagecomment, update the MyViewModel:

          public class ImageComment
        {
            public int Id { get; set; }
     
            public string Title { get; set; }
            public string Comment { get; set; }
        }
    
        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; }
    
            public bool CanComment { get; set; }
    
        }
    
    
        public class MyContext : DbContext
        {
            public MyContext(DbContextOptions<MyContext> options)
                : base(options)
            {
            }
            public DbSet<ImageComment> ImageComments { get; set; }
        }
    
    

    4.Register the Dbcontext in dependency Injection

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

    5.Run the following commands in the Package Manager Console or terminal to apply migrations and create the database:

    add-migration InitialCreate
    update-database
    
    

    6.Create the IcommentService and manage the comments

        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()
            {
                return  _context.ImageComments.ToList();
            }
        }
    

    7.Modify the component:

    @page "/PageBu"
    
    @inject ICommentService CommentService
    @rendermode @(new InteractiveServerRenderMode(prerender: false))
    <h3>PageBu</h3>
    
    <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 {
        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);
    
     
        }
    }
    
    

    Result:

    User's image

     


    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.

    1 person found this answer helpful.

15 additional answers

Sort by: Most helpful
  1. AgaveJoe 28,536 Reputation points
    2024-08-17T14:20:31.26+00:00

    I can see you are building a Blazor application but your question is not clear. I think you are asking how to save data in a database but I'm not sure. I recommend going through tutorial a few tutorials to learn data access basics. The following tutorial illustrates how to implement a solution with Entity Entity Framework Core and Core

    ASP.NET Core Blazor with Entity Framework Core (EF Core)

    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  4. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

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.