Модальное / Частичное представление Великобритании Дата конфликта MVC5 - PullRequest
0 голосов
/ 03 января 2019

У меня проблема с проверкой jquery в модальном / частичном представлении, поскольку это противоречит моему основному представлению.Основная проблема связана с @ Scripts.Render ("~ / bundles / jqueryval"), поскольку, когда я добавляю ее в свой основной вид, основная форма больше не отправляется (не попадает в контроллер), так как проверка отклоняет британский стильдаты (как вы можете видеть в моем коде, я использую DateITA для решения этой проблемы в моем Модальном и отправляет без проблем)

Я попытался переместить @ Scripts.Render ("~ / bundles / jqueryval")к частичному представлению, и главная страница теперь будет отправлена, но это нарушит мою отправку для Модального.Я также попытался назвать форму основного вида и модальную форму, чтобы применить проверку только к модальному, но это не помогло.

Спасибо

Главный вид

@model Puspers2.ViewModels.ContractViewModel
@{
    ViewBag.Title = "Contract";
}

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "mainForm" }))
{

 <div class="form-group form-inline datepickerWidth">
                        <div class='input-group date mydatepicker datepickerWidth'>

                            @Html.TextBoxFor(m => m.TblContract.OrderPlacedDate, new { title = "Order Placed Date", placeholder = "dd/mm/yyyy", @class = "form-control datepickerWidth", onclick = "this.select()", id = "orderPlacedDate" })
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>

                    </div>

<div class='form-group form-inline datepickerWidth'>
                        <div class='input-group date mydatepicker datepickerWidth'>

                            @Html.TextBoxFor(m => m.TblContract.ContractStartDate, new { title = "Contract Start Date", placeholder = "dd/mm/yyyy", @class = "form-control datepickerWidth", id = "contractStartDate", onclick = "this.select()" })
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </span>
                        </div>
                    </div>


  <!--SAVE BUTTON-->
            <br /><br /><br /><br />
            <div class="form-group absolute">
                <hr />
                <button type="submit" class="btn btn-primary btn-lg saveButtonPadding" value="save" formaction="ContractUpdate" formmethod="post" id="saveButton">Save</button>
            </div>
            <!--SAVE BUTTON-->


}


<!--div to hold the Partial view that forms the modal-->
<div class="form-group">
    @Html.Partial("_ContractContributionDetails")
</div>
<!--end div to hold the Partial view that forms the modal-->


@section scripts{

   @Scripts.Render("~/bundles/jqueryval")

    <script>

        //Modal

        $(document).on('click', '#SaveContractContribution', function () {           

            var $form = $('#modalForm')

            .validate({
                rules: {
                    TblContractContributionHistory_CommencementDeductions: {
                        dateITA: true
                    }
                }
            });

            if ($form.valid()) {

                $.ajax({

                    async: false,
                    type: 'POST',
                    url: 'ContractContributionHistoryAdd',
                    datatype: "json",
                    data: {
                        contractNumber: $("#contractNumber").val(),
                        commencementDeductions: $('#TblContractContributionHistory_CommencementDeductions').val(),
                        deductionsCategoryId: $('#deductionsCategory').val(),
                        numberOfContributions: $('#TblContractContributionHistory_NumberOfContributions').val(),
                        employeeContributionReference: $('#TblContractContributionHistory_EmployeeContributionReference').val(),
                        teamMember: $('#TblContractContributionHistory_TeamMemberId').val()

                    },

                    success: function (data) {
                        location.reload();
                    }
                });
            }
        });


 // >> JS snippet to handle datepicker functionality >>
        $(function () {
            $('.mydatepicker').datetimepicker({
                locale: 'en-gb',
                format: 'DD/MM/YYYY',
                showTodayButton: true,
                showClear: true,

            })
            .on('dp.hide', function () {    // on hiding data picker, record associated entryfield to allow focus to be set when built-in blur happens
                dateField = $(this).find('input');
                $("#contractStartDate,#contractEndDate,#actualTerminationDate").trigger("change")
                PickerClosing = true;
            });

            // on exit from date field, check if caused by picker closing. If Yes, set focus back in field
            $('.mydatepicker input').blur(function (e) {
                if (PickerClosing == true) {
                    PickerClosing = false;
                    dateField.focus();
                }
            });

        });
        // << JS snippet to handle datepicker functionality <<


 </script>

}

Частичное представление

@model Puspers2.ViewModels.ContractViewModel
@Scripts.Render("~/Scripts/jquery-1.10.2.js")
@Scripts.Render("~/Scripts/jquery-3.3.1.js")
@Scripts.Render("~/scripts/jquery-ui-1.12.1.min.js")
@Scripts.Render("~/scripts/bootbox.js")
@Scripts.Render("~/Scripts/bootstrap.js")
@Scripts.Render("~/Scripts/respond.js")
@Scripts.Render("~/Scripts/moment.js")
@Scripts.Render("~/Scripts/moment-with-locales.js")
@Scripts.Render("~/Scripts/bootstrap-datetimepicker.js")

@{

}

@using (Ajax.BeginForm("ContractContributionHistoryAdd", "Home", new AjaxOptions
{ }, new { id = "modalForm" }))
{
    <div>
        <!-- Modal -->
        <div class="modal fade" id="myModal" role="dialog">

            <div class="modal-dialog">

                <!-- Modal content-->
                <div class="modal-content modalContentDeductions">

                    <h2 class="modal-header">Add Deduction</h2>

                    <div class="modal-body">     

                        <p class="dateLabels"><strong>Deductions Commenced On</strong></p>

                        <div class='form-group form-inline modalDatepickerWidth'>
                            <div class='input-group date mydatepicker modalDatepickerWidth'>

                                @Html.TextBoxFor(m => m.TblContractContributionHistory.CommencementDeductions, new { title = "Commencement Deductions", @class = "form-control inputSizeMedium" })
                                <span class="input-group-addon">
                                    <span class="glyphicon glyphicon-calendar"></span>
                                </span>
                            </div>
                        </div>                    

                         <div class='form-group'>

                            @Html.LabelFor(m => m.TblContractContributionHistory.DeductionsCategoryId, new { title = "Payment" })
                            @Html.DropDownListFor(m => m.TblContractContributionHistory.DeductionsCategoryId, new SelectList(Model.TblDeductionsCategoryLOOKUP, "DeductionsCategoryId", "Category"), "Select Option", new { @class = "form-control inputSizeMedium", @id="deductionsCategory"})
                            @Html.ValidationMessageFor(m => m.TblContractContributionHistory.DeductionsCategoryId)
                        </div> 

                        <div class="form-group">

                            @Html.LabelFor(m => m.TblContractContributionHistory.EmployeeContributionReference, new { title = "Monthly Cost To Employee" })
                            @Html.TextBoxFor(m => m.TblContractContributionHistory.EmployeeContributionReference, new { title = "Monthly Cost To Employee", @class = "form-control inputSizeMedium" })

                        </div>

                        <div class="form-group">

                            @Html.LabelFor(m => m.TblContractContributionHistory.NumberOfContributions, new { title = "" })
                            @Html.TextBoxFor(m => m.TblContractContributionHistory.NumberOfContributions, new { title = "", @class = "form-control inputSizeMedium" })

                        </div>

                        <div class='form-group'>

                            @Html.LabelFor(m => m.TblContractContributionHistory.TeamMemberId, new { title = "" })
                            @Html.DropDownListFor(m => m.TblContractContributionHistory.TeamMemberId, new SelectList(Model.TblTeamMembersLOOKUP, "TeamMemberId", "TeamMemberName"), "Select Option", new { @class = "form-control inputSizeMedium" })
                            @Html.ValidationMessageFor(m => m.TblContractContributionHistory.TeamMemberId)
                        </div>  

                        <br />

                        <div>
                            <button id="SaveContractContribution" class="btn btn-primary btn-lg" value="save" formmethod="post">Save</button>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>

                </div>
            </div>
        </div>
    </div>
}


@section scripts
{

<script>    

    $(function () {
        $.validator.unobtrusive.parse('#modalForm');
    });

    $(function () {
        $('.mydatepicker').datetimepicker({
            locale: 'en-gb',
            format: 'DD/MM/YYYY',
            showTodayButton: true,
            showClear: true,

        })
        .on('dp.hide', function () {    // on hiding data picker, record associated entryfield to allow focus to be set when built-in blur happens
            dateField = $(this).find('input');
            $("#contractStartDate,#contractEndDate,#actualTerminationDate").trigger("change")
            PickerClosing = true;
        });

        // on exit from date field, check if caused by picker closing. If Yes, set focus back in field
        $('.mydatepicker input').blur(function (e) {
            if (PickerClosing == true) {
                PickerClosing = false;
                dateField.focus();
            }
        });
    })

  </script>
}

DateITA

$.validator.addMethod( "dateITA", function( value, element ) {
    var check = false,
        re = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
        adata, gg, mm, aaaa, xdata;
    if ( re.test( value ) ) {
        adata = value.split( "/" );
        gg = parseInt( adata[ 0 ], 10 );
        mm = parseInt( adata[ 1 ], 10 );
        aaaa = parseInt( adata[ 2 ], 10 );
        xdata = new Date( Date.UTC( aaaa, mm - 1, gg, 12, 0, 0, 0 ) );
        if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth() === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) {
            check = true;
        } else {
            check = false;
        }
    } else {
        check = false;
    }
    return this.optional( element ) || check;
}, $.validator.messages.date );
...