I am working on ASP.NET Core web site using Razor Pages instead of MVC.
I faced a situation where I have to implement a shared component which can be used in different pages. The component is - Simple comments thread. On different pages signed users can send their comments.
The component should consist of 2 parts:
- Comments List - this is the list of comments which can be easily implemented with either ViewComponent or Partial Page;
- Add comment control - this is textarea and submit button which allow user to send their own comment.
What I want to achieve is to use ViewComponent or Partial page or some other technique to put some markup with initial parameters on any page to enable this comments functionality without copy/pasting same code from page to page.
And I have a few issues with this.
As I already mentioned, ViewComponent can be used to show the list of comments on any page just by adding the following markup:
@await Component.InvokeAsync("Comments", new { type="NewsItem", id="@Model.Item.ID" })
So CommentsViewComponent will call ef.core DBContext to load comments for defined type and id. This works perfect. But the issue start to happen when I need to send posts from ViewComponent's markup and handle these posts.
It is planned to have 3 possible post calls:
- Add new comment
- Delete existing comment
- Edit existing comment
The first possible approach is to define 3 handlers on NewsItem page and call them using tag-helper from ViewComponent. But then i would have to define 3 same handlers on any other page where i would need the same functionality.
Another approach which I was thinking about is to define some fake PageModel which would contain these 3 handlers and ViewComponent would post to this page using Ajax. The only complication here is that after doing these posts I need to force ViewComponent to rerender itself since Comments were changed (deleted, added or edited).
So as a result the component would contains of the following parts:
- ViewComponent to show necessary markup
- JavaScript code to send posts on client clicks
- Fake PageModel to handle posts.
I don't really like this approach and I think it is too complex for such a simple task. This is my first APS.NET core Razor Pages project so I don't have much experience on how to implement such isolated components and hope you guys could guide me on how this could be implemented in a better way to follow SOLID and DRY principles.
Thanks.