I have two buttons on my HTML page inside a form using the "POST" method. On click of first button, a function in the model called "OnPostSubmitBtn()" would fire up, calling another class a doing a bunch of calculations to an input that I have received in a textbox in the same form, this would then put it in an outputbox in the same form. The second button, is to clear both boxes. When it is clicked, a function in the model called "OnPostClearBtn()" would fire up, clearing both boxes.
On the same HTML page but below this form, I am displaying the below information. This information is filled by the OnGet() method in the model. Inside this "OnGEt()" method, I am establishing a connection to a database, getting the information back and adding it to a list.
The problem is that every time I click on Submit or clear, the contents below are gone (Contents filled from the database into the tables below). It seems like the OnGet method is only executed once and every time I click on a button, a new instance is made, but the OnGet method is not firing, rightfully..
public class Comments
{
public string name { get; set; }
public string email { get; set; } = "NULL"; // default null
public string comment { get; set; } = "No Comment";
public string createdAt { get; set; }
}
<h2>Comments</h2>
<table >
<thead>
<tr>
<th>Name</th>
<th>Comment</th>
<th>Time of creation: </th>
</tr>
</thead>
<tbody>
@foreach(var item in Model.comments){
<tr>
<td>@item.name</td>
<td>@item.comment</td>
<td>@item.createdAt </td>
</tr>
}
</tbody>
</table>
There are two ways to solve the problem but I am sure they are just a walk around and not real solutions someone would using int he professional world. You can call the OnGet() method again in both OnSubmit buttons, or I can move my database connection and populating the list from the OnGet to the Model's constructor, because it will be called every time.
I am sure there are professional ways to do it, or is doing it the way I did it sufficient enough? What would be the equivalent function that would be called every time regardless of whether its a new instance or not?
CodePudding user response:
If you want the same data available in both the OnGet
and OnPost
methods, the workaround you have identified is the correct one - call the database in both handlers. Usually, you would write one private method in your PageModel class that does this then call that method in the relevant handler.
I would avoid putting this in the constructor because it is not usual to need exactly the same data for both get and post methods. Often, you only need data in a post method if model validation fails and you need to redisplay the form. Also, you might add other handler methods at some point in the future that don't need it at all.