Reputation: 1
Is there a way to format a string directly inside of quickgrid
I can get and display the information without any issue, I would just like to format the data to look clean inside of the table
<PropertyColumn Title="Phone Number:" Property="@(u => u.Phone)" />
<PropertyColumn Title="Phone Number:" Format="{0:###-###-####}" Property="@(u => u.Phone)" />
What I tried using earlier, it just deleted the Phone Property Column
I have Phone saved as the following inside of a DTO
[Required, MaxLength(11), DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
I did find out that the Format feature is an IFormattable Object
I tried to create a PhoneFormatterClass and use that to pass user.Phone, and convert to an IEnumerable, then pass to the Format="@PhoneNumber"
This result was Ok, and didn't cause any errors, data was displayed, just not the format I was looking for
FormatPhoneNumber in Razor Page, ManageUsers
private void FormatPhoneNumber(UserDTO user)
{
if(user.Phone != null)
try
{
var phoneNumber = user.Phone;
string formatNumber = PhoneFormatter.FormatPhoneNumber(phoneNumber);
return;
}
catch (Exception ex)
{
_errorMessage = ex.Message;
}
}
Here is the PhoneFormatter.cs File I was trying to use
public class PhoneFormatter
{
public static string FormatPhoneNumber(IEnumerable<char> phoneNumber)
{
// Filter out non-digit characters
var digits = phoneNumber.Where(char.IsDigit).ToArray();
// Ensure we have exactly 10 digits
if (digits.Length != 10)
{
throw new ArgumentException("Phone number must contain exactly 10 digits.");
}
// Format the phone number
return $"({new string(digits.Take(3).ToArray())}) {new string(digits.Skip(3).Take(3).ToArray())}-{new string(digits.Skip(6).Take(4).ToArray())}";
}
}
Added Entire User Razor Page
<SectionContent SectionName="pageTitle">Manage Users</SectionContent>
<div class="card mb-3">
<div class="card-header d-flex flex-row">
<h5 class="flex-fill">Users</h5>
<div class="px-1">
<select class="form-select form-select-sm" onchange="OnPageSizeChanged">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
@* <button class="btn btn-sm btn-info" @onclick="OnAddUser">Add New User</button> *@
</div>
</div>
<div class="row">
<div class="col-sm-3 ms-auto mb-3">
<label class="form-label"> Filter by Approved Status</label>
<select class="form-control" @bind="_filter" @bind:after="OnFilterChangedAsync">
@foreach (var f in Enum.GetValues<UserApprovedFilter>())
{
<option value="@f">@f</option>
}
</select>
</div>
</div>
<div class="col-lg-12 control-section">
<div class="content-wrapper">
<div class="row">
<div class="edddata">
<DropDownListFieldSettings Text="Text" Value="Value"></DropDownListFieldSettings>
</div>
</div>
</div>
</div>
<div class="row">
<QuickGrid ItemsProvider="_usersProvider" @ref="_grid" Pagination="_paginationState" Class="Table" ItemKey="@(u => u.Id)" >
<PropertyColumn Title="Id:" Property="@(u => u.Id)" Sortable="true" InitialSortDirection="SortDirection.Ascending"/>
<PropertyColumn Title="First Name:" Property="@(u => u.FirstName)" />
<PropertyColumn Title="Last Name:" Property="@(u => u.LastName)" />
<PropertyColumn Title="Phone Number:" Property="@(u => u.Phone)" />
<PropertyColumn Title="Email:" Property="@(u => u.Email)"/>
<PropertyColumn Title="Address:" Property="@(u => u.Address)" />
<PropertyColumn Title="City:" Property="@(u => u.City)" />
<PropertyColumn Title="State:" Property="@(u => u.State)" />
<PropertyColumn Title="Zip Code:" Property="@(u => u.Zip)" />
<PropertyColumn Title="Role:" Property="@(u => u.Role)" Sortable="true">
<ColumnOptions>
<label>
<input type="checkbox" @bind="ShowRole" /> Show Role
<hr />
<button onclick="@OnFilterChangedAsync">Reset</button>
</label>
</ColumnOptions>
</PropertyColumn>
<TemplateColumn Title="Is Approved?">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" checked="@(context.IsApproved)"
role="switch" id="[email protected]" @onchange="() => OnUserApprovedToggleAsync(context)" />
<label class="form-check-label" for="[email protected]">
@(context.IsApproved ? "Yes" : "No")
</label>
</div>
</TemplateColumn>
</QuickGrid>
<Paginator State="_paginationState" />
</div>
@code {
private const int DefaultPageSize = 10;
private QuickGrid<UserDTO>? _grid;
private string nameFilter = string.Empty;
private GridItemsProvider<UserDTO> _usersProvider;
private string? _role;
private bool? ShowRole = null;
private UserApprovedFilter _filter = UserApprovedFilter.All;
private PaginationState _paginationState = new PaginationState { ItemsPerPage = DefaultPageSize };
protected override void OnInitialized()
{
_usersProvider = async request =>
{
AppState.ShowLoader("Fetching users, please standby.");
var pagedResult = await UserAPI.GetUsersAsync(_filter, request.StartIndex, request.Count ?? DefaultPageSize);
AppState.HideLoader();
return GridItemsProviderResult.From(pagedResult.Records, pagedResult.TotalCount);
};
}
private async Task UserRoleChangedAsync(UserDTO user)
{
_role = user.Role;
_shouldReRender = false;
AppState.ShowLoader("Updating user role, please standby.");
await UserAPI.ChangeUserRoleAsync(user.Id);
_shouldReRender = true;
AppState.HideLoader();
}
private async Task OnUserApprovedToggleAsync(UserDTO user)
{
user.IsApproved = !user.IsApproved;
_shouldReRender = false;
AppState.ShowLoader("Updating status, please standby.");
await UserAPI.ToggleUserApprovedStatusAsync(user.Id);
_shouldReRender = true;
AppState.HideLoader();
}
private bool _shouldReRender = true;
protected override bool ShouldRender() => _shouldReRender;
private async Task OnFilterChangedAsync()
{
if (_grid != null)
await _grid.RefreshDataAsync();
}
}
Here is the API Class
using Refit;
namespace .Web.APIs
{
[Headers("Authorization: Bearer ")]
public interface IUserAPI
{
[Get("/api/users")]
Task<PagedResult<UserDTO>> GetUsersAsync(UserApprovedFilter approveType, int startIndex, int pageSize);
[Get("/api/users")]
Task<PagedResult<UserDTO>> GetUsersAsync(UserRole userRole);
[Patch("/api/users/{userId}/change-role")]
Task ChangeUserRoleAsync(int userId);
[Patch("/api/users/{userId}/toggle-status")]
Task ToggleUserApprovedStatusAsync(int userId);
}
}
Error with adding Format section inside of the PropertyColumn :
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: A 'Format' parameter was supplied, but the type 'System.String' does not implement 'System.IFormattable'.
System.InvalidOperationException: A 'Format' parameter was supplied, but the type 'System.String' does not implement 'System.IFormattable'.
at Microsoft.AspNetCore.Components.QuickGrid.PropertyColumn`2[[xxxx.Shared.DTOs.Users.UserDTO, AceManager.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].OnParametersSet()
at Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
at Microsoft.AspNetCore.Components.ComponentBase.SetParametersAsync(ParameterView parameters)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters)
Upvotes: 0
Views: 105