ASP.NET Core MVC Ajax在成功返回html页面后在页面中仅显示json吗?

问题描述 投票:0回答:1

基本上,我从控制器调用SendInvoince方法,并发送发票!问题在于ajax发布成功后,数据是html页面,而不是从controller方法返回的json,弹出swal错误,并在1秒后刷新页面,显示仅包含controller返回的json的页面! ????为什么?发生了什么事?

这是我的控制器:

    [HttpPost]
    public IActionResult SendInvoice(Document document)
    {
        bool success = false;
        string errorMessage = null;

        string session = GetSession();

        document.Docktype = "4";

        try
        {
            document.Id = InsertDocumentHeader(document, session);

            InsertDocumentLine(document, session);                

            document.Id = CloseDocument(document, session);

            Client client = GetClient(session, document.NIF);                

            SendDocumentPDF2Email(document, session, client.Email);

            success = true;
        }
        catch (Exception e)
        {
            errorMessage = e.Message;
        }                                                       

        return Json(new { success, Error = errorMessage });
    }      

这是我的观点:

 @{
      ViewData["Title"] = "Home Page";
  }

  @model WebApplication2.Controllers.HomeController.HomeModel

 <style>
     .required:after {
         content: " *";
         color: red;
     }

     .control-label {
         margin-left: 2%;
     }
 </style>

 <div>
     <div id="AddClientModal" class="modal">
         <div class="modal-dialog modal-lg">
             <div class="modal-content">
                 <div class="modal-header">
                     <h4 class="modal-title">Add Client</h4>
                     <button type="button" class="close" data-dismiss="modal">X</button>
                 </div>
                 <br />
                 <form action="@Url.Action("CreateClient", "Home")" method="post" id="addClientForm">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                     <b style="color:red; margin-left: 2%; ">* </b>Required field
                     <br />
                     <div class="form-group">
                        @Html.LabelFor(model => model.Client.NIF,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.NIF,
                        new { htmlAttributes = new { @class = "form-control", @id = "clientNIF" } })
                             @Html.ValidationMessageFor(model => model.Client.NIF,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Name,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Name,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Name,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Address,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Address,
                        new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Client.Address,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Locality,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Locality,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Locality,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.PostalCode,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.PostalCode,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.PostalCode,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Email,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Email,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Email,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Fax,
                    htmlAttributes: new { @class = "control-label" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Fax,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Fax,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Phone,
                    htmlAttributes: new { @class = "control-label required" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Phone,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Phone,
                        "", new { @class = "text-danger" })
                         </div>
                    </div>
                     <div class="form-group">
                         @Html.LabelFor(model => model.Client.Obs,
                    htmlAttributes: new { @class = "control-label" })
                         <div class="col-md-8">
                             @Html.EditorFor(model => model.Client.Obs,
                        new { htmlAttributes = new { @class = "form-control" } })
                             @Html.ValidationMessageFor(model => model.Client.Obs,
                        "", new { @class = "text-danger" })
                         </div>
                     </div>
                 </form>
                 <div class="modal-footer">
                     <button id="btnAddClientFormSubmit" class="btn btn-success" form="addClientForm" type="button">Create</button>
                     <button id="btnAddClientFormCancel" class="btn btn-danger" type="button">Cancel</button>
                 </div>
             </div>
         </div>
     </div>

<div>
    <div id="SendInvoiceModal" class="modal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Send Invoice</h4>
                    <button type="button" class="close" data-dismiss="modal">X</button>
                </div>
                <br />
                <form action="@Url.Action("SendInvoice", "Home")" method="post" id="SendInvoiceForm">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <b style="color:red; margin-left: 2%; ">* </b>Required field
                    <br />
                    <div class="form-group">
                        @Html.LabelFor(model => model.Client,
                        htmlAttributes: new { @class = "control-label required" })
                        <div class="col-md-8">
                            @Html.DropDownListFor(model => model.Document.NIF,
                            Model.Clients.Select(x => new SelectListItem { Text = x.Name, Value = x.NIF }), null,
                            new { htmlAttributes = new { @class = "form-control", @id = "optClientNIF" } })
                            @Html.ValidationMessageFor(model => model.Document.NIF,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.Obs,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.Obs,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.Obs,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.DocRef,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.DocRef,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.DocRef,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.Qt,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.Qt,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.Qt,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.Price,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.Price,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.Price,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.Tax,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.Tax,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.Tax,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Document.ProdDesc,
                        htmlAttributes: new { @class = "control-label" })
                        <div class="col-md-8">
                            @Html.EditorFor(model => model.Document.ProdDesc,
                            new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Document.ProdDesc,
                            "", new { @class = "text-danger" })
                        </div>
                    </div>
                </form>
                <div class="modal-footer">
                    <button id="btnSendInvoiceFormSubmit" class="btn btn-success" form="SendInvoiceForm" type="submit">Create</button>
                    <button id="btnSendInvoiceFormCancel" class="btn btn-danger" type="button">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <div>
        <button id="AddClientModalBtn" class="btn btn-primary" type="button">Insert Client</button>
        <button id="SendInvoiceModalBtn" class="btn btn-primary" type="button">Send Invoice</button>
    </div>

    <div class="card shadow mb-4" style="margin-top: 3%;">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Clients</h6>
        </div>
        <div class="card-body" style="margin-bottom: 1rem">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Client.NIF)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Name)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Address)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Locality)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.PostalCode)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Email)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Fax)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Phone)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Obs)</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Client.NIF)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Name)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Address)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Locality)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.PostalCode)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Email)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Fax)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Phone)</th>
                            <th>@Html.DisplayNameFor(model => model.Client.Obs)</th>
                        </tr>
                    </tfoot>
                    <tbody>
                        @foreach (Client row in Model.Clients)
                        {
                            <tr id="@row.NIF">
                                <td>@row.NIF</td>
                                <td>@row.Name)</td>
                                <td>@row.Address</td>
                                <td>@row.Locality</td>
                                <td>@row.PostalCode</td>
                                <td>@row.Email</td>
                                <td>@row.Fax</td>
                                <td>@row.Phone</td>
                                <td>@row.Obs</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript" src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="~/lib/limonte-sweetalert2/sweetalert2.min.js"></script>
@*<script type="text/javascript" src="~/lib/datatables/js/jquery.dataTables.js"></script>
    <script type="text/javascript" src="~/lib/datatables/js/dataTables.bootstrap4.js"></script>*@
@{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>

    function CheckNIF(NIF) {
        var isValid = false;            

        const arrayNIF = Array.from(String(NIF), Number);

        var sum = 0;
        var multi = 9;

        for (var i = 0; i < arrayNIF.length - 1; i++) {
            sum += arrayNIF[i] * multi;
            multi--;
        }

        var result = sum % 11;

        if (result == 0 || result == 1) {
            result = 0;
        }
        else {
            result = 11 - result;
        }

        if (result == arrayNIF[8]) {
            isValid = true;
        }
        else {
            isValid = false;
        }

        return isValid;
    }

    $(document).ready(function () {            

        $('#AddClientModalBtn').click(function () {
            $("#AddClientModal").modal('show');
        });            

        $('#btnAddClientFormSubmit').click(function () {

            var NIF = document.getElementById('clientNIF').value

            if (CheckNIF(NIF)) {
                $("#addClientForm").submit();
            }
            else {
                console.log("Error");
                swal.fire({
                    position: 'top',
                    type: 'error',
                    title: 'Invalid NIF',
                    text: 'Please enter a valid NIF',
                    allowOutsideClick: false,
                });
            }
        });

        $('#btnAddClientFormCancel').click(function () {
            $("#AddClientModal").modal('hide');
            $("#addClientForm").trigger('reset');
        });

        $('#SendInvoiceModalBtn').click(function () {
            $("#SendInvoiceModal").modal('show');
        });

        $('#btnSendInvoiceFormCancel').click(function () {
            $("#SendInvoiceModal").modal('hide');
            $("#SendInvoiceForm").trigger('reset');
        });

        $(function () {
            $('#addClientForm').submit(function () {
                $.ajax({
                    url: this.url,
                    type: this.method,
                    data: $(this).serialize(),                        
                    success: function (data) {                            
                        if (data.success) {
                            Swal.fire({
                                position: 'top-end',
                                type: 'success',
                                title: 'Client added.',
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                            });
                            console.log("Success");
                        }
                        else {
                            Swal.fire({
                                type: 'error',                                    
                                text: 'Error adding client. If the problem persists, please contact the support.',
                                allowOutsideClick: false,
                            });
                            console.log("Server Error");
                        }
                    },
                    error: function () {
                        console.log("Request failed");                            
                    }
                });
            });
        });

        $(function () {
            $('#SendInvoiceForm').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: this.url,
                    type: this.method,                        
                    data: $(this).serialize(),                        
                    success: function (data) {
                        console.log("HELLO");
                        console.log(data);
                        console.log(data.length);
                        console.log(data.success);
                        if (data.success) {
                            Swal.fire({
                                position: 'top-end',
                                type: 'success',
                                title: 'Invoice sent.',
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                            });
                            console.log("Success");
                        }
                        else {
                            Swal.fire({                                    
                                type: 'error',
                                text: 'Error sending invoice. If the problem persists, please contact the support.',
                                allowOutsideClick: false,
                            });
                            console.log("Server Error");
                        }
                    },
                    error: function () {
                        console.log("Request failed");                            
                    }
                });
            });
        });
    });
</script>

这是console.logs(console.log(data),console.log(data.lenght),console.log(data.success)):

enter image description here

这是ajax发布后的页面:enter image description here

最诚挚的问候!

ajax post asp.net-core-mvc response
1个回答
0
投票

花了一段时间后,我发现使用:ajax url的this.url是问题!!!

之前:

$(function () {
        $('#SendInvoiceForm').submit(function (event) {
            event.preventDefault();
            $.ajax({
                url: this.url,
                type: this.method,                        
                data: $(this).serialize(), 

SndInvoiceForm作为操作:

<form action="@Url.Action("SendInvoice", "Home")" method="post" id="SendInvoiceForm">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <b style="color:red; margin-left: 2%; ">* </b>Required field

不知道为什么它不起作用?

之后:

 $(function () {
            $('#SendInvoiceForm').submit(function (event) {
                event.preventDefault();
                $.ajax({
                    url: '@Url.Action("SendInvoice", "Home")',
                    type: this.method,
                    data: $(this).serialize(),

现在有效!!!!如果有人知道为什么,请让我知道!

© www.soinside.com 2019 - 2024. All rights reserved.