twitter bootstrap – modal form validation after using select2

I am using partialview in modal form. In this form there is a select2 option list which working fine. But when you press submit button, required fields as per model are not validating ie not showing error.

I have used lots of option from internet, but failed to get the desired result.

When we remove the select2 field from partialview, it’s working fine.

Cust_Mast.cs Model

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace IDESK.Models.Customer
{
    public class Cust_Master
    {
        [Key]
        [Display(Name = "CUST_CODE")]
        [Required(ErrorMessage = "Please enter Customer Code")]
        public int  CUST_CODE { get; set; }

        [Display(Name = "CUST_NAME")]
        [Required(ErrorMessage = "Please enter Customer Name")]
        [MaxLength(50)]
        public string CUST_NAME { get; set; }

        [Display(Name = "CUST_REGN")]
        [Required(ErrorMessage = "Please enter Customer Regn")]
        [MaxLength(20)] 
        public string CUST_REGN { get; set; }

        [Display(Name = "SALES_ORG")]
        [Required(ErrorMessage = "Please enter Customer Sales Orgn.")]
        [MaxLength(20)]
        public string  SALES_ORG { get; set; }

        [Display(Name = "CUST_GROUP")]
        [Required(ErrorMessage = "Please enter Customer Customer Group")]
        [MaxLength(20)] 
        public string CUST_GROUP { get; set; }

        [Display(Name = "INCO_TERMs")]
        [Required(ErrorMessage = "Please enter Inco Term")]
        [MaxLength(5)]
        public string INCO_TERMS { get; set; }

        [Display(Name = "BILL_CURRENCY")]
        [Required(ErrorMessage = "Please enter Bill Currency")]
        [MaxLength(5)]
        public string BILL_CURCY { get; set; }

        [Display(Name = "Is Pallet?")]
        public bool IsPallet { get; set; }

    }
}

Index.cshtml

@model IEnumerable<IDESK.Models.Customer.Cust_Master>
<!DOCTYPE html>
@*<div id="notification"></div>*@

<div id="modal-placeholder"></div>
@Html.AntiForgeryToken()

<body class="hold-transition sidebar-mini">
    <div class="wrapper">
        <h4 style="color:indigo">Customer Master Index</h4>
        <form method="post" enctype="multipart/form-data" asp-action="UploadFileData">

            <button type="button" class="btn btn-primary" data-bs-toggle="ajax-modal" data-bs-target="#customer_model"
                    data-url="@Url.Action("Create",new {Model })">
                <i class="fa fa-plus"></i>
                Create
            </button>
            <input type="submit" id="thisbutton" value="Upload data" class="btn btn-primary" />
            @{
                <!--accept="csv/CSV"-->
                if (TempData["upload"] == "OK")
                {
                    @Html.ActionLink("Save List", "SaveList", new { action = "SaveList" }, new { @class = "btn btn-secondary small" })
                }
            }
            <div>
                <input type="file" id="fileName" name="fileName" accept="Text/CSV" title="Select a file" style="margin-top:5px" />
            </div>
        </form>

        @{
            if (TempData["Message"] != null)
            {
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            @Html.Raw(TempData["Alert"])
                        </div>
                    </div>
                </div>
            }
        }

        @await Html.PartialAsync("_tblCustomer", Model)



    </div>
</body>
@section Scripts {
    @*<script src="~/lib/jquery/jquery.min.js"></script>*@
    <script src="~/lib/jquery-validation/dist/validate.min.js"></script>
    <script src="/lib/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

    <partial name="_ValidationScriptsPartial" />
    <script type="text/javascript">

 

        $('body').on('shown.bs.modal', '.modal', function () {
            $(this).find('select').each(function () {
                var dropdownParent = $(document.body);
                
                if ($(this).parents('.modal.in:first').length !== 0)
                    dropdownParent = $(this).parents('.modal.in:first');
                $(this).select2({
                    dropdownParent: $('#customer_model'), //dropdownParent
                    
                });
                //$("select").on("select2:close", function (e) { //---this for all
                $("#ddlCustGroup").on("select2:close", function (e) { //---this for specific.
                    //$(this).valid();
                    $(this).trigger('blur');
                });

                $('#customer_model').validate({
                    ignore: null
                });

                $select.rules('add', 'required');

            });
        });


        @* $(document).ready(function () {

            $('button').click(function () {
                // $(this).valid();
                //if ($(this).valid())

                $('.modal-header').load('@Url.Action("ShowMsg")');
                //  $('.modal-title').append("<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-bs-dismiss="alert" aria-hidden='true'>&times;</button>Success</div>")
                //else
                //   $('.modal-body').append("<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-bs-dismiss="alert" aria-hidden='true'>&times;</button>Failed</div>")
            })

        });*@

        $.validator.unobtrusive.parse('#myForm');
    </script>
}

_Customer.cshtml –partialview.

@model IDESK.Models.Customer.Cust_Master;
@{
    Layout = null;
    
}

<link href="~/lib/select2/css/select2.css" rel="stylesheet" />
<script src="~/lib/select2/js/select2.js"></script>

<script src="~/lib/jquery-validation/dist/validate.min.js"></script>
<script src="/lib/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="~/lib/twitter-bootstrap/js/bootstrap.js"></script> <!--For modal form-->
@*https://softdevpractice.com/blog/asp-net-core-mvc-ajax-modals/*@
@Html.AntiForgeryToken()
<div id="modal-placeholder"></div>
<div class="modal fade" id="customer_model" tabindex="-1" role="dialog" aria-labelledby="customer_modelLabel"
     data-bs-backdrop="static" data-bs-keyboard="false" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" id="movableDialog" role="document">
        <div class="modal-content" style="background-color: white; color: black; width: 600px; margin-left: auto; margin-right: auto">
            <div class="modal-header" style="background-color: #337ab7; color: white; cursor: move">
                @{
                    if (ViewBag.action == "Edit")
                    { <h6 class="modal-title text-center" id="customer_modelLabel">Update Raw Material</h6> }
                    else if (ViewBag.action == "Delete")
                    { <h6 class="modal-title" id="customer_modelLabel" style="color:darkorange">Shown Material will be deleted.<br />Please confirm?</h6> }
                    else
                    { <h6 class="modal-title" id="customer_modelLabel" style="text-align:center;">Create Raw Material</h6> }
                }
                @*<h4 class="modal-title" id="rawmaterialLabel" style="text-align:center">Create Raw Material</h4>*@
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true" style="color:darkred">×</span>
                </button>
            </div>
            <div class="modal-body">

                <form asp-action="Create" id="myForm">
                    <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
                    <div class="form-group">
                        <div class="col-md-10">
                            <div class="form-inline">
                                <label asp-for="CUST_CODE" class="control-label col-sm-4"></label>
                                <input asp-for="CUST_CODE" readonly class="form-control col-md-4" style="color:darkgoldenrod;" />
                                <span asp-validation-for="CUST_CODE" class="text-danger"></span>
                            </div>
                            <div class="form-inline" style="margin-top:5px">
                                <label asp-for="CUST_NAME" class="control-label col-sm-4"></label>
                                <input asp-for="CUST_NAME" class="form-control col-md-8" />
                                <span asp-validation-for="CUST_NAME" class="text-danger"></span>
                            </div>
                            <div class="form-inline" style="margin-top:5px">
                                <label asp-for="CUST_GROUP" class="control-label col-sm-4"></label>
                                <select asp-for="CUST_GROUP" class="form-control select2-results  col-md-6" id="ddlCustGroup" name="CUST_GROUP" asp-items="@(new SelectList(ViewBag.CustGroup, "Value", "Text"))">
                                    <option value="">---Select Customer Group---</option>
                                </select>
                                <input type="hidden" name="CUST_GROUP" value="@Model.CUST_GROUP" />
                                <span asp-validation-for="CUST_GROUP" class="text-danger"></span>
                            </div>
                            <div class="form-inline" style="margin-top:5px">
                                <label asp-for="CUST_REGN" class="control-label col-sm-4"></label>
                                <input asp-for="CUST_REGN" class="form-control col-md-6" />
                                <span asp-validation-for="CUST_REGN" class="text-danger"></span>
                            </div>

                        </div>
                    </div>
                    @{
                        if (ViewBag.action == "Edit")
                        {
                            <div class="form-group">
                                <div class="col-md-10">
                                    @*<input type="submit" value="Save" class="btn btn-primary" />*@
                                    <input type="hidden" name="action" value="Edit" />
                                    <input type="hidden" name="id" value="@Model.CUST_CODE" />
                                    @*<span><a asp-action="Index" class="btn btn-primary">Back to List</a> </span>*@
                                </div>
                            </div>
                        }
                        else if (ViewBag.action == "Delete")
                        {
                            <div class="form-group">
                                <div class="col-md-10">
                                    @*<input type="submit" value="Delete" class="btn btn-danger" />*@
                                    <input type="hidden" name="action" value="Delete" />
                                    <input type="hidden" name="id" value="@Model.CUST_CODE" />
                                    @*<span><a asp-action="Index" class="btn btn-primary">Back to List</a> </span>*@
                                </div>
                            </div>
                        }
                        else
                        {
                            <div class="form-group">
                                <div class="col-md-10">
                                    @*<input type="submit" value="Create" class="btn btn-primary" />*@
                                    <input type="hidden" name="action" value="Create" />
                                    @*<span><a asp-action="Index" class="btn btn-primary">Back to List</a> </span>*@
                                </div>
                            </div>
                        }
                    }
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                @{
                    if (ViewBag.action == "Delete")
                    {
                        <button type="button" class="btn btn-primary" data-bs-save="modal">Delete</button>
                    }
                    else
                    {
                        <button type="button" class="btn btn-primary" data-bs-save="modal">Save</button>
                    }
                }
            </div>
        </div>
    </div>

</div>
<script type="text/javascript">

    $('#customer_model').bind("viewtransfer", function () {

        $('#myForm').removeData('validator');

        $('#myForm').removeData('unobtrusiveValidation');

        $.validator.unobtrusive.parse('#myForm');

    });


    //$("#myForm").removeData("validator")
    //    .removeData("unobtrusiveValidation")
    //    .off("submit.validate click.validate focusin.validate focusout.validate keyup.validate invalid-form.validate");
    //$.validator.unobtrusive.parse("#myForm");
   
    </script>

—Site.js—-

//const { Alert } = require("./lib/twitter-bootstrap/js/bootstrap.esm.js");

// Write your JavaScript code.

$(function () {
   
    var placeholderElement = $('#modal-placeholder');
    $.validator.setDefaults({
        ignore: ""
    });
    //$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
    $(document).on('click', 'button[data-bs-toggle="ajax-modal"]', function (event) {
        var url = $(this).data('url');
        $.get(url).done(function (data) {
            placeholderElement.html(data);
            placeholderElement.find('.modal').modal('show');
            
        });
    });

    placeholderElement.on('click', '[data-bs-save="modal"]', function (event) {
        event.preventDefault();
        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var dataToSend = form.serialize();
        
        $.post(actionUrl, dataToSend).done(function (data) {
            var newBody = $('.modal-body', data);
            placeholderElement.find('.modal-body').replaceWith(newBody);

            var isValid = newBody.find('[name="IsValid"]').val() == 'True';
            if (isValid) {
                //$('#notification').text('Data saved successfully!');
                //location.reload();
                //placeholderElement.find('.modal').modal('hide');

                var tableElement = $('#tblName');
                var tableUrl = tableElement.data('url');
                $.get(tableUrl).done(function (table) {
                    tableElement.replaceWith(table);
                });

            }
            else { 
            //    $('#notification').text('Data operation failed!');
                
                
                placeholderElement.find('.modal').modal('show');
                bootstrap.Alert();
            }
            
            bootstrap.Alert();
            placeholderElement.find('.modal').modal('hide');
           
        });
    });
});


Leave a Comment