This example demonstrates how to display an error message from the Web API Service when the criteria is not met during editing.
In the Web API Service controller, return a bad request error when the edited value does not meet the criteria.
public async Task<IActionResult> PutProducts(int id, Products products) {
if (id != products.ProductId) {
return BadRequest();
}
if (products.UnitPrice < 0) {
return BadRequest("Unit Price cannot be less than 0");
}
_context.Entry(products).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
In the razor page, handle the DxGrid.EditModelSaving event to get the error message from the Web API service. Then, set the event's e.Cancel
property to true
.
private string MyErrorMessage { get; set; }
async Task Grid_EditModelSaving(GridEditModelSavingEventArgs e) {
MyErrorMessage = null;
var editedProduct = (Products)e.EditModel;
var httpContent = ConvertProductToHttpContent(editedProduct);
var response = e.IsNew == false
? await HttpClient.PutAsync(ProductsUrl + editedProduct.ProductId, httpContent)
: await HttpClient.PostAsync(ProductsUrl, httpContent);
if (response.IsSuccessStatusCode)
Products = await LoadDataAsync();
else {
e.Cancel = true;
MyErrorMessage = await response.Content.ReadAsStringAsync();
}
}
Display the error message in the EditFormTemplate
.
<EditFormTemplate Context="editFormContext">
<DxFormLayout>
<DxFormLayoutItem Caption="Name">
@editFormContext.GetEditor("ProductName")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Price">
@editFormContext.GetEditor("UnitPrice")
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Discontinued">
@editFormContext.GetEditor("Discontinued")
</DxFormLayoutItem>
@if (String.IsNullOrEmpty(MyErrorMessage) == false) {
<DxFormLayoutItem ColSpanMd="12">
<div style="color:red">@MyErrorMessage</div>
</DxFormLayoutItem>
}
</DxFormLayout>
</EditFormTemplate>
(you will be redirected to DevExpress.com to submit your response)