Ajax 到 MVC POST 请求:重定向问题,"Page not working"

Ajax to MVC POST request: Redirection issue, "Page not working"

在我的 Post 请求(从 AJAX 到控制器)之后我遇到了一个小问题。基本上,post 请求发生,它执行控制器中的函数,however,在它执行 ajax 调用后,我得到以下页面:

我不知道为什么会这样,希望能得到一些帮助。我以前没有接触过这种东西。 以下是一些可以提供帮助的代码片段:

已编辑 .js 文件:

    function Export() {
   

    var donations = new Array();
    $("#Donations tbody tr").each(function () {
        var row = $(this);
        var donation = {};
        donation.Name = row.find("td").eq(0)[0].innerText;
        donation.DOB = row.find("td").eq(1)[0].innerText;
        donation.DOD = row.find("td").eq(2)[0].innerText;
        donation.COD = row.find("td").eq(3)[0].innerText;
        donation.CaseNumber = row.find("td").eq(4)[0].innerText;
        donations.push(donation);
    });

    
    $.ajax({
        type: "POST",
        url: "/Donation/Export",
        data: JSON.stringify(donations),
        dataType: "json",
        success: function (data) {
            console.log("file saved: ", data);            
        }
    }).done(function () {
        window.location.href = '@Url.Action("Download", "DonationController", new { csv = data }))';
    });;
};

已编辑 Index.cshtml:

 @using (Html.BeginForm())
{

    <p>
        <input type="submit" class="btn btn-outline-primary btn-sm" value="Export" onclick="Export()" />

    </p>


    <table id="Donations" class="table">
        <thead>
            <tr>
                <th>Full Name</th>
                <th>@Html.DisplayNameFor(model => model.Person.DateOfBirth)</th>
                <th>@Html.DisplayNameFor(model => model.Donation.DateOfDeath)</th>
                <th>@Html.DisplayNameFor(model => model.Donation.CauseOfDeath)</th>
                <th>@Html.DisplayNameFor(model => model.Donation.CaseNumber)</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Donations)
            {
                <tr>
                    <td><a asp-action="Details" asp-controller="Person" asp-route-id="@item.PersonId">@Html.DisplayFor(modelItem => item.Person.Title) @Html.DisplayFor(modelItem => item.Person.Forenames) @Html.DisplayFor(modelItem => item.Person.Surname)</a></td>
                    <td>@Html.DisplayFor(modelItem => item.Person.DateOfBirth)</td>
                    <td>@Html.DisplayFor(modelItem => item.DateOfDeath)</td>
                    <td>@Html.DisplayFor(modelItem => item.CauseOfDeath)</td>
                    <td><a asp-action="Details" asp-controller="Donation" asp-route-id="@item.PersonId">@Html.DisplayFor(modelItem => item.CaseNumber)</a></td>
                </tr>
            }
        </tbody>
    </table>
}

已编辑 DonationController.cs:

[HttpPost]
        public string Export()
       
        {
                    
            var resolveRequest = HttpContext.Request;         
           
            string[] columnNames = { "Name", "DOB","DateOfDeath", "CauseOfDeath", "CaseNumber" };

            //Build the CSV file data as a Comma separated string.
            string csv = string.Empty;

            foreach (string columnName in columnNames)
            {
                //Add the Header row for CSV file.
                csv += columnName + ',';
            }

            //Add new line.
            csv += "\r\n";

            foreach (string k in resolveRequest.Form.Keys)
            {
                using JsonDocument doc = JsonDocument.Parse(k);
                JsonElement root = doc.RootElement;;
                var users = root.EnumerateArray();

                while (users.MoveNext())
                {
                    var user = users.Current;
                    var props = user.EnumerateObject();

                    while (props.MoveNext())
                    {
                        var prop = props.Current;                        
                        csv += String.IsNullOrEmpty(prop.Value.ToString()) ? "," : prop.Value.ToString().Replace(",", ";") + ',';
                        //Console.WriteLine($"{prop.Name}: {prop.Value}");
                    }
                    csv += "\r\n";
                }

                
            }           
            
            
            return (csv);
            
            
        }

        public FileContentResult Download(string csv)
        {
            //Download the CSV file.
            byte[] bytes = Encoding.ASCII.GetBytes(csv);
            return File(bytes, "application/text", "Donations.csv");
           
    }

无法将文件作为查询字符串传递,这将导致负载格式不受支持。这将导致 415 error.

在你的Export方法中(IActionResult,return a Jsonresult):

[HttpPost]
public IActionResult Export([FromBody] List<ExportedValues> values)
    {
      //...
      return new JsonResult (new {csv = csv });
    }

然后在您的 Download 方法中:

 public FileContentResult Download(string csv)
   {
       return File(//Convert to your file)
   }

在你的ajax中:

$.ajax({
    type: "POST",
    url: "/Donation/Export",
    data: JSON.stringify(donations),
    dataType: "json",
    success: function (data) {
                console.log("file saved: ", data);
                window.location = '/Donation/Download?csv=' + data.csv;
            }
        });