So i’m coding a small basic razor page project, and i’m kinda stuck on this part, i don’t know if the CategoryId data actually got send to the back-end for process. I don’t really know much about javascript i ask my friends for a javascript code to send some data to the back-end . Here is the code
Note: the page is UserMainPage.cshtml and UserMainPage.cshtml.cs
Sorry if it a bit mess, this code is for the user to sort out the event using their category.
In UserMainPage.cshtml
<div style="position: relative; margin-left: auto;">
<select style="height: 40px; border: 1px solid #ddd; border-radius: 4px; padding-left: 10px; font-size: 16px;" id="categorySelect">
<option value="" hidden>Category</option>
@if (Model.TblCategory != null && Model.TblCategory.Any())
{
foreach (var category in Model.TblCategory)
{
<option value="@category.CategoryId">@category.CategoryName</option>
}
}
else
{
<option value="0">No categories found</option>
}
</select>
</div>
Here are the script
<script>
var categorySelect = document.getElementById('categorySelect');
categorySelect.addEventListener('change', function () {
var categoryId = parseInt(categorySelect.value); // convert to integer
window.location.href = "./UserMainPage?categoryId=" + categoryId;
});
</script>
In UserMainPage.cshtml.cs
public async Task<IActionResult> OnPostAsync(int? categoryId, string searchString)
{
if (categoryId == null && string.IsNullOrEmpty(searchString))
{
// If no category is selected and search string is null or empty, return all events
TblEvent = await _context.TblEvents
.Include(t => t.Admin)
.Include(t => t.Category)
.Include(t => t.Location)
.ToListAsync();
}
else if (categoryId != null)
{
// Filter events by category
TblEvent = await _context.TblEvents
.Include(t => t.Admin)
.Include(t => t.Category)
.Include(t => t.Location)
.Where(t => t.CategoryId == categoryId)
.ToListAsync();
}
else if (!string.IsNullOrEmpty(searchString))
{
// Filter events by search string
TblEvent = await _context.TblEvents
.Include(t => t.Admin)
.Include(t => t.Category)
.Include(t => t.Location)
.Where(t => t.EventName.Contains(searchString))
.ToListAsync();
}
return Page();
}