Friday, 11 October 2019

How to create function to validate dropdownlist in the backend

I am developing a small form with the help of C# and ASP.NET MVC and within this form I have a dropdownlist which shows some enabled states this depends on the value that comes in the form that in this case would be FINISHED.

I would like to place some restriction from the back-end to avoid that if the users change the values ​​of disabled from the console of the navigator, it does not allow him to send them, to validate in the controller that those data are not sent.

The following is the code dropdownlist with its different options

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<select id="ticketStatusInput" name="status" class="form-control form-control-user" style="width: 100%; padding: 0.375rem 0.75rem; height: 50px;" tabindex="-1" aria-hidden="true">
                                        <option value="" disabled="" selected="">Select a option</option>

                                    <option value="ABT" disabled="">OPEN</option><option value="ASG">ASSIGNED</option><option value="CDO" disabled="">CLOSED</option><option value="ESU" disabled="">WAITING FOR USER</option><option value="PRC">IN PROCESS</option><option value="TMN">FINISHED</option></select>

This is the Javascript function which loads the data and the realization of its respective validation, it is clear that TMN corresponds to the FINISHED state .

function loadTicketDetails() {
    $(".fixed-action-btn").floatingActionButton();
    $(".fixed-action-btn").show("slow");
    $('[data-toggle="tooltip"]').tooltip();
    document.getElementById("modalAceptNew").style.display = "none";

    const url = document.getElementById("allTicketData").value;

    window.hasRun = true;

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        success: function (data) {

            $("#StatusDiv select").val(data.Status);

            //Validation when FINISHED can be assigned to ASSIGNED/IN PROCESS
            if (data.Status == 'TMN') {

                $("#StatusDiv select option[value*='ABT']").prop("disabled", true);
                $("#StatusDiv select option[value*='CDO']").prop("disabled", true);
                $("#StatusDiv select option[value*='ESU']").prop("disabled", true);
            } 

        },
        error: function() {
            alert("There was an error loading the data, please try again.");
        }
    });

}

And finally the controller which is where some validation should be done in the back

[HttpPost]
public JsonResult UpdateTicketFromDetails()
        {
            var ticketStatusInput = Request.Form["ticketStatusInput"];
        try
            {
                TicketRegisterResult result;               
                using (var scope = new TransactionScope())
                {
                    // I create a new record variable with all fields
                    var record = new TK_DT_RECORDS
                    {
                        TK_CT_STATUS_ID = ticketStatusInput,
                    };
                    // We update the ticket data (this will always be done)
                    var model = new TicketRegisterModel();
                    // We create the new record in the record table and insert it
                    result = model.UpdateTicket;

                    //If the ticket was not saved, the transaction is finished and we return the error message
                    if (!result.Success)
                        return Json(new TicketResult
                        {
                            IsValid = false,
                            Error = "The changes could not be saved, please try again."
                        });
                    scope.Complete();
                }   
            }catch (DbEntityValidationException ex)
        {
            //Failed to try to register data in the database
            foreach (var e in ex.EntityValidationErrors)
            foreach (var validationError in e.ValidationErrors)
                Console.WriteLine("Property: " + validationError.PropertyName + " Error: " +
                                  validationError.ErrorMessage);

            return Json(new TicketResult
            {
                IsValid = false,
                Error = "There was an error creating the ticket, please try again."
            });
        }
            return Json(new TicketResult
            {
                IsValid = true
            });
            }

The data will always be sent, because I have no control over that. what I need is a function that allows to control if the data is valid.

I found an article that talks about controller side data validation but it is not very clear to me as soon as I start with C#

Article



from How to create function to validate dropdownlist in the backend

No comments:

Post a Comment