We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

CRUD Actions in Scheduler - add server side validation with response message

How do I add server-side validation in CRUD operations and return an error message to the user that the database write has been aborted?

Additionally, how do I refresh the data only from a previously selected date range after saving data (

public ActionResult LoadData([FromBody] LoadParams param)

{

var data = GetEventsData().Where(a=>a.StartTime >= param.StartDate && a.EndTime <=param.EndDate);

return Json(data);

}

[HttpPost]

public ActionResult UpdateData([FromBody] EditParams param)

{

if (param.action == "insert" || (param.action == "batch" && param.added != null)) // this block of code will execute while inserting the appointments

{

var value = (param.action == "insert") ? param.value : param.added[0];

if (value.Subject.Length > 100) Console.WriteLine("To long");//how to display message??

else

{

Console.WriteLine("Write to db");

//db.SubmitChanges();

}

}

var data = GetEventsData();//how to refresh data with time range?

return Json(data);

}


Attachment: AspnetcoreSync_93fceade.zip


3 Replies

RV Ravikumar Venkatesan Syncfusion Team January 12, 2023 08:43 PM UTC

Hi Lukasz,


Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ej_core_schedule_crud_with_server_side_validation-1050652874


Q1: How do I add server-side validation in CRUD operations and return an error message to the user that the database write has been aborted?

You can validate and return an error message with the help of the actionFailure event of the Schedule as shown in the below code snippet.


UG: https://ej2.syncfusion.com/aspnetcore/documentation/schedule/data-binding#handling-failure-actions


[Index.cshtml]

<ejs-schedule id="schedule" height="550" selectedDate="DateTime.Now.Date" actionFailure="onActionFailure">

    <e-schedule-eventsettings>

        <e-data-manager url="/Index?handler=LoadData" crudUrl="/Index?handler=UpdateData" adaptor="UrlAdaptor"></e-data-manager>

    </e-schedule-eventsettings>

</ejs-schedule>

 

<script type="text/javascript">

    function onActionFailure(args) {

        if(args.error && args.error.length > 0) {

            var scheduleObj = document.querySelector('.e-schedule').ej2_instances[0];

            var span = document.createElement('span');

            scheduleObj.element.parentNode.insertBefore(span, scheduleObj.element);

            span.style.color = '#FF0000';

            span.innerHTML = args.error[0].error.response;

        }

    }

</script>


[Index.cshtml.cs]

        public IActionResult OnPostUpdateData([FromBody] EditParams param)

        {

 

            if (param.action == "insert" || (param.action == "batch" && param.added.Count > 0)) // this block of code will execute while inserting the appointments

            {

                var value = (param.action == "insert") ? param.value : param.added[0];

 

                if(value.Subject.Length > 20)

                {

                    return BadRequest("Subject value exceeds maximum length 20");

                }

           }

        }


Q2: how do I refresh the data only from a previously selected date range after saving data

The data loaded from the LoadData method only binds to the Schedule. Also, you can receive the start and end dates of the current view in the LoadData method. So, you can filter the appointments based on the current view date range and return them to the Schedule. Also, if you don’t want to return the entire appointment list from the UpdateData method, you can return the received param alone, as highlighted in the below code snippet.


[Index.cshtml.cs]

        public IActionResult OnPostLoadData([FromBody] Params param)

        {

 

            var data = _context.Appointments.Where(app => app.StartTime >= param.StartDate && app.EndTime <= param.EndDate).ToList();

            return new JsonResult(data);

 

        }

 

        public IActionResult OnPostUpdateData([FromBody] EditParams param)

        {

 

            return new JsonResult(param);

        }

    }


Regards,

Ravikumar Venkatesan



LU Lukasz February 9, 2023 06:29 PM UTC

Dear  Ravikumar,

Thanks for response.

But how to return reponse messege also for success actions? Like "Ok, events XYZ created sucessfully".


For the second question I have found better solution, extended EditParams class with two new fields:

    

public class EditParams
    {
        public string key { get; set; }
        public string action { get; set; }
        public List<ScheduleEvent> added { get; set; }
        public List<ScheduleEvent> changed { get; set; }
        public List<ScheduleEvent> deleted { get; set; }
        public ScheduleEvent value { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }


After that I can download data from specific period:

var data = _dataRepository.GetEvents(param.StartDate, param.EndDate);
return new JsonResult(data);





RV Ravikumar Venkatesan Syncfusion Team February 10, 2023 10:36 PM UTC

Lukasz,


Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ej2-core-schedule-crud-with-response-message156498965


You can return a response message for successful action as shown in the below code snippet. If you want to show an alert to the user you need to create a CustomAdaptor by overriding the UrlAdaptor as shown in the below code snippet.


[index.cshtml.cs]

        public IActionResult OnPostUpdateData([FromBody] EditParams param)

        {

            var message = "";

            if (param.action == "insert" || (param.action == "batch" && param.added.Count > 0)) // this block of code will execute while inserting the appointments

            {

 

                message = value.Subject + " added sucessfully.";

            }

            if (param.action == "update" || (param.action == "batch" && param.changed.Count > 0)) // this block of code will execute while removing the appointment

            {

                _context.SaveChanges();

               message = value?.Subject + " updated sucessfully.";

            }

            if (param.action == "remove" || (param.action == "batch" && param.deleted.Count > 0)) // this block of code will execute while updating the appointment

            {

                _context.SaveChanges();

                message = "Appointment removed sucessfully.";

            }

            var data = _context.Appointments.Where(app => app.StartTime >= param.StartDate && app.EndTime <= param.EndDate).ToList();

            var response = new { data = data, message = message };

            return new JsonResult(response);

        }

    }


[index.cshtml]

<ejs-schedule id="schedule" height="550" selectedDate="DateTime.Now.Date" created="onCreated" actionFailure="onActionFailure" actionComplete="onActionComplete">

</ejs-schedule>

 

<script type="text/javascript">

    function onCreated(args) {

        // Creating a custom adaptor by extending the default UrlAdaptor

        class CustomAdaptor extends ej.data.UrlAdaptor {

            processResponse(data, ds, query, xhr, request, changes) {

                if (!ej.base.isNullOrUndefined(data.message)) {

                    alert(data.message);

                }

                if (!ej.base.isNullOrUndefined(data.data))

                    return data.data;

                else

                    return data;

            }

        }

        var scheduleObj = document.querySelector(".e-schedule").ej2_instances[0];

        scheduleObj.eventSettings.dataSource = new ej.data.DataManager({

            url: "/Index?handler=LoadData",

            crudUrl: "/Index?handler=UpdateData",

            adaptor: new CustomAdaptor()

        });

        scheduleObj.dataBind();

    }

</script>


Also, you can use the actionComplete event of the Schedule instead of returning the response message from the server. The actionComplete event of the Schedule will be triggered once the appointment is successfully added, updated, or deleted from the server. You can get the respective appointment details at this event.


[index.cshtml]

    function onActionComplete(args) {

        if (["eventCreated", "eventChanged", "eventRemoved"].indexOf(args.requestType) > -1) {

            if(args.addedRecords.length > 0) {

                alert(args.addedRecords[0].Subject +  " added.");

            }

            if(args.changedRecords.length > 0) {

                alert(args.changedRecords[0].Subject + " updated.");

            }

            if (args.deletedRecords.length > 0) {

                alert(args.deletedRecords[0].Subject + " deleted.");

            }

        }

    }


Loader.
Live Chat Icon For mobile
Up arrow icon