ASP.NET Core MVC Controls | ComponentOne
Working with Controls / CollectionView / Work with CollectionView / Validation
In This Topic
    Validation
    In This Topic

    CollectionView provides validation support to show custom or multiple errors in the FleGrid row header cells. The CollectionView provides GetError property to offer validation support. When you use the CollectionView.GetError method for validation, the FlexGrid shows errors in data cells and also in the row header cells. All the errors in the entire data item are included in the error message, by default. This message makes the information more useful and our data grid more user-friendly.

    By default, the row header cells shows all the errors in the item. To customize that behavior, return the error message you want to show for the row header when the GetError method is called without a specific property (prop == null). You can also perform your own validation using a custom function when items are edited.

    Showing Validation in FlexGrid with errors can be seen in the data cells as well as row headers

    The following sample uses the GetError function to only allow certain countries and positive numbers to be committed. The example uses Sale.cs model added in the Custom Editors topic.

    Controller Code

    ValidationController.cs
    Copy Code
    public class HomeController : Controller
    {
        private static List<Sale> ValidationSales = Sale.GetValidationData().ToList();
        public IActionResult Index()
        {
            return View(ValidationSales);
        }
    
        public ActionResult GridUpdateSale([C1JsonRequest] CollectionViewEditRequest<Sale> requestData)
        {
            return this.C1Json(CollectionViewHelper.Edit<Sale>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    var resultItem = ValidationSales.Find(s => s.ID == item.ID);
                    var index = ValidationSales.IndexOf(resultItem);
                    ValidationSales.Remove(resultItem);
                    ValidationSales.Insert(index, item);
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<Sale>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => ValidationSales));
        }
    
        public ActionResult GridCreateSale([C1JsonRequest] CollectionViewEditRequest<Sale> requestData)
        {
            return this.C1Json(CollectionViewHelper.Edit<Sale>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    ValidationSales.Add(item);
                    item.ID = ValidationSales.Max(s => s.ID) + 1;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<Sale>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => ValidationSales));
        }
    
        public ActionResult GridDeleteSale([C1JsonRequest] CollectionViewEditRequest<Sale> requestData)
        {
            return this.C1Json(CollectionViewHelper.Edit<Sale>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    var resultItem = ValidationSales.Find(u => u.ID == item.ID);
                    ValidationSales.Remove(resultItem);
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<Sale>
                {
                    Error = error,
                    Success = success,
                    Data = item
                };
            }, () => ValidationSales));
        }
    }
    

    View Code

    Index.cshtml
    Copy Code
    @using C1.Web.Mvc
    @using CVErrorReport_Core.Models
    
    @model List<Sale>
    
    <script type="text/javascript">
        var validCountries = ["US", "UK", "Canada", "Japan", "China", "France", "German", "Italy", "Korea", "Australia"];
        var validProducts = ["Widget", "Gadget", "Doohickey"];
        function getError(item, property) {
            switch (property) {
                case 'Country':
                    return validCountries.indexOf(item[property]) < 0
                        ? '@Html.Raw("Invalid Country, Please use the country in the list[US, UK, Canada, Japan, China, France, German, Italy, Korea, Australia]")'
                        : null;
                case 'Product':
                    return validProducts.indexOf(item[property]) < 0
                        ? '@Html.Raw("Invalid Product, Please use the product in the list [Widget, Gadget, Doohickey]")'
                        : null;
                case 'Amount2':
                    return item[property] < 0 || item[property] >= 5000
                        ? '@Html.Raw("The Amount cannot be less than 0 or greater than or equal to 5000!")'
                        : null;
                case 'Active':
                    return item[property] && item['Country'] && item['Country'].match(/US|UK/)
                        ? '@Html.Raw("Active items are not allowed in the US or UK!")'
                        : null;
            }
            return null;
        }
    </script>
    
    <style>
        .text-style-errortip {
            background-color: lightyellow;
            color: red;
            font-style: oblique;
            text-shadow: 2px 2px 5px orangered;
        }
    
        .strong-round-errortip {
            background-color: lightgoldenrodyellow;
            color: red;
            border-radius: 10%;
        }
    </style>
    
    <c1-items-source id="validationCV" get-error="getError"
                     source-collection="Model"
                     update-action-url="@Url.Action("GridUpdateSale")"
                     create-action-url="@Url.Action("GridCreateSale")"
                     delete-action-url="@Url.Action("GridDeleteSale")">
    </c1-items-source>
    
    <c1-flex-grid id="DemoControl" auto-generate-columns="false"
                  allow-add-new="true" allow-delete="true" height="400px"
                  items-source-id="validationCV" validate-edits="true">
        <c1-flex-grid-column binding="ID" is-read-only="true"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Product"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Country"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Color"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Amount2"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Discount"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Active"></c1-flex-grid-column>
        <c1-flex-grid-errortip class="text-style-errortip" position="Above"></c1-flex-grid-errortip>
    </c1-flex-grid>