|
| 1 | +@page "/" |
| 2 | + |
| 3 | +@using pre_validate_item_for_grid_state_init.Models |
| 4 | +@using pre_validate_item_for_grid_state_init.Services |
| 5 | +@using System.ComponentModel.DataAnnotations; |
| 6 | +@inject WeatherForecastService ForecastService |
| 7 | + |
| 8 | +<TelerikButton OnClick="@CreateHandler">Add Forecast</TelerikButton> |
| 9 | +<TelerikButton OnClick="@DiscardHandler">Discard current forecast being edited with annotation message</TelerikButton> |
| 10 | +<TelerikTextArea @bind-Value="@TextAreaValue" Label="Message:" AutoSize="true" Enabled="false"></TelerikTextArea> |
| 11 | +<TelerikGrid @ref="grid" Data="@forecasts" Height="550px" FilterMode="@GridFilterMode.FilterMenu" |
| 12 | + Sortable="true" Pageable="true" PageSize="20" Groupable="true" Resizable="true" Reorderable="true" |
| 13 | + OnUpdate="@UpdateHandler" OnDelete="@DeleteHandler" EditMode="@GridEditMode.Incell"> |
| 14 | + <GridColumns> |
| 15 | + <GridColumn Field="Id" Title="Id" Width="100px" Editable="false" Groupable="false" /> |
| 16 | + <GridColumn Field="Date" Width="220px" DisplayFormat="{0:dddd, dd MMM yyyy}" /> |
| 17 | + <GridColumn Field="TemperatureC" Title="Temp. C" DisplayFormat="{0:N1}" /> |
| 18 | + <GridColumn Field="TemperatureF" Title="Temp. F" DisplayFormat="{0:N1}" /> |
| 19 | + <GridColumn Field="Summary" /> |
| 20 | + <GridCommandColumn Width="90px" Resizable="false"> |
| 21 | + <GridCommandButton Command="Delete" Icon="delete"></GridCommandButton> |
| 22 | + </GridCommandColumn> |
| 23 | + </GridColumns> |
| 24 | +</TelerikGrid> |
| 25 | + |
| 26 | + |
| 27 | +@code { |
| 28 | + List<WeatherForecast> forecasts { get; set; } |
| 29 | + protected TelerikGrid<WeatherForecast> grid { get; set; } |
| 30 | + protected string TextAreaValue { get; set; } |
| 31 | + protected override async Task OnInitializedAsync() |
| 32 | + { |
| 33 | + await GetForecasts(); |
| 34 | + } |
| 35 | + |
| 36 | + async Task GetForecasts() |
| 37 | + { |
| 38 | + forecasts = await ForecastService.GetForecastListAsync(DateTime.Now); |
| 39 | + } |
| 40 | + |
| 41 | + public async Task DeleteHandler(GridCommandEventArgs args) |
| 42 | + { |
| 43 | + TextAreaValue = ""; |
| 44 | + WeatherForecast currItem = args.Item as WeatherForecast; |
| 45 | + |
| 46 | + await ForecastService.DeleteForecastAsync(currItem); |
| 47 | + |
| 48 | + await GetForecasts(); |
| 49 | + } |
| 50 | + // Note that the "Add Forecast" button must not be in the grid (like the grid header) |
| 51 | + // If it is, it will be frozen and not clickable. |
| 52 | + public async Task CreateHandler() |
| 53 | + { |
| 54 | + TextAreaValue= ValidateGridState(true); // This will tell the user that there is a data problem with the grid that needs correcting |
| 55 | + if (TextAreaValue != "") return; |
| 56 | + |
| 57 | + WeatherForecast currItem = new WeatherForecast(); |
| 58 | + |
| 59 | + await ForecastService.InsertForecastAsync(currItem); |
| 60 | + |
| 61 | + await GetForecasts(); |
| 62 | + } |
| 63 | + |
| 64 | + public async Task DiscardHandler() |
| 65 | + { |
| 66 | + TextAreaValue = ""; |
| 67 | + var gridState = grid.GetState(); |
| 68 | + if (gridState.EditItem == null) return; // We are not editing anything so nothing to discard |
| 69 | +
|
| 70 | + ValidateGridState(false); // If you try to discard without calling this method, the grid will remain in a locked state |
| 71 | +
|
| 72 | + await ForecastService.DeleteForecastAsync(gridState.OriginalEditItem); |
| 73 | + |
| 74 | + await GetForecasts(); |
| 75 | + } |
| 76 | + |
| 77 | + public async Task UpdateHandler(GridCommandEventArgs args) |
| 78 | + { |
| 79 | + TextAreaValue = ""; |
| 80 | + WeatherForecast currItem = args.Item as WeatherForecast; |
| 81 | + |
| 82 | + await ForecastService.UpdateForecastAsync(currItem); |
| 83 | + |
| 84 | + await GetForecasts(); |
| 85 | + } |
| 86 | + protected string ValidateGridState(bool isSave) // Change the bool name isSave for your needs |
| 87 | + { |
| 88 | + // When you click off a Telerik Grid in in-cell mode, there are cases where current edited cell does not close. |
| 89 | + // The two cases found thus far are when a cell fails validation via annotations or |
| 90 | + // when you are using an edit template like a DDL |
| 91 | + // this behavior with the editor template is documented in the editor template notes |
| 92 | + // https://docs.telerik.com/blazor-ui/components/grid/editing/incell#editor-template |
| 93 | + // For the cell validation case, Telerik locks the entire grid until you do something with the cell. Even if you |
| 94 | + // try to reload the grid on a discard, the grid will remain frozen even though the row/cell in question is gone. |
| 95 | + // |
| 96 | + // This function cleans up that mess by restoring the original item when you just want to discard |
| 97 | + // the current data or returns the data annotation error message on a save. |
| 98 | + // With this function, you can keep SAVE/DISCARD/CLOSE (or your CRUD functions) active for all grid edit types. |
| 99 | + // You could also use this approach before loading state into the grid (in OnStateInit) to ensure your users will have |
| 100 | + // a workable grid even if they left off in an invalid state when they saved their session |
| 101 | + // In this example the method returns a string that is put in a textarea, you can show it to the user |
| 102 | + // in any other way, such as with a TelerikNotification or a Telerik alert dialog |
| 103 | +
|
| 104 | + if (grid == null) return ""; |
| 105 | + |
| 106 | + var gridState = grid.GetState(); |
| 107 | + if (gridState.EditItem != null) |
| 108 | + { |
| 109 | + if (isSave) |
| 110 | + { |
| 111 | + // For the save case, validate the EditItem object |
| 112 | +
|
| 113 | + // This post was very helpful in figuring this out: https://www.c-sharpcorner.com/UploadFile/20c06b/using-data-annotations-to-validate-models-in-net/ |
| 114 | + ICollection<ValidationResult> results = new List<ValidationResult>(); |
| 115 | + if (!Validator.TryValidateObject(gridState.EditItem, new ValidationContext(gridState.EditItem), results, true)) |
| 116 | + { |
| 117 | + // Failed validation - should just be one failure since we are doing in-cell editing |
| 118 | + return String.Join("", results.Select(o => $"- {o.ErrorMessage}")); |
| 119 | + } |
| 120 | + } |
| 121 | + else |
| 122 | + { |
| 123 | + // Discard case - just reset the field with the original value to allow the |
| 124 | + // grid to be in a good state if the field in question failed validation via annotations |
| 125 | + var currentDataFields = gridState.EditItem; // Get the row data containing the cell that is being edited |
| 126 | + var originalDataFields = gridState.OriginalEditItem; // Get the original data |
| 127 | + var currentDataField = currentDataFields.GetType().GetProperty(gridState.EditField); // EditField is the name of the field we are editing (string name) |
| 128 | + var originalDataField = originalDataFields.GetType().GetProperty(gridState.EditField); |
| 129 | + var originalDataValue = originalDataField.GetValue(originalDataFields); |
| 130 | + currentDataField.SetValue(currentDataFields, originalDataValue); // Reset the current value with the original value |
| 131 | + } |
| 132 | + } |
| 133 | + return ""; |
| 134 | + } |
| 135 | +} |
0 commit comments