Ajax到MVC POST请求:重定向问题,“页面无法正常工作" [英] Ajax to MVC POST request: Redirection issue, "Page not working"

查看:83
本文介绍了Ajax到MVC POST请求:重定向问题,“页面无法正常工作"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我发出Post请求(从AJAX到控制器)后,我遇到了一个小问题.基本上,发布请求发生了,它执行了控制器中的功能但是,在执行ajax调用之后,我得到了以下页面:

我不知道为什么会发生这种情况,我将不胜感激.我以前没有处理过这种东西.以下是一些可以帮助您的代码段:

已编辑 .js 文件:

 函数Export(){var捐赠= 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({类型:"POST",网址:"/Donation/Export",数据:JSON.stringify(捐赠),dataType:"json",成功:功能(数据){console.log(文件已保存:",数据);}}).done(function(){window.location.href ='@ Url.Action("Download","DonationController",new {csv = data)))'';});;}; 

已编辑 Index.cshtml:

  @using(Html.BeginForm()){< p><输入类型=提交";class ="btn btn-outline-primary btn-sm";value =导出"onclick ="Export()";/></p>< table id ="Donations";class ="table">< thead>< tr>< th>全名</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(Model.Donations中的var项){< tr>< td>< asp-action =详细信息"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>< asp-action =详细信息"asp-controller =捐赠".asp-route-id ="@ item.PersonId"> @ Html.DisplayFor(modelItem => item.CaseNumber)//td.</tr>}</tbody></table>} 

已编辑 DonationController.cs:

  [HttpPost]公共字符串Export(){var resolveRequest = HttpContext.Request;string [] columnNames = {名称","DOB","DateOfDeath","CauseOfDeath","CaseNumber";};//将CSV文件数据构建为逗号分隔的字符串.字符串csv = string.Empty;foreach(columnNames中的字符串columnName){//添加CSV文件的标题行.csv + = columnName +',';}//添加新行.csv + ="\ r \ n";foreach(resolveRequest.Form.Keys中的字符串k){使用JsonDocument doc = JsonDocument.Parse(k);JsonElement root = doc.RootElement ;;var users = root.EnumerateArray();同时(users.MoveNext()){var user = users.Current;var props = user.EnumerateObject();同时(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";}}返回(csv);}公共FileContentResult下载(字符串csv){//下载CSV文件.byte [] bytes = Encoding.ASCII.GetBytes(csv);返回文件(字节,应用程序/文本","Donations.csv");} 

解决方案

文件不能作为查询字符串传递,这将导致有效载荷格式不受支持.这将导致 415错误.

在您的 Export 方法中( IActionResult,返回Jsonresult ):

  [HttpPost]公共IActionResult导出([FromBody] List< ExportedValues>值){//...返回新的JsonResult(新的{csv = csv});} 

然后在您的 Download 方法中:

  public FileContentResult下载(字符串csv){返回文件(//转换为文件)} 

在您的ajax中:

  $.ajax({类型:"POST",网址:"/Donation/Export",数据:JSON.stringify(捐赠),dataType:"json",成功:功能(数据){console.log(文件已保存:",数据);window.location ='/Donation/Download?csv ='+ data.csv;}}); 

I am having a tiny issue after my Post request (from AJAX to the controller). Basically, the post request takes place, it executes the function in the controller, however, after it executes the ajax call, I get the following page:

I don't know why that is happening, and I would appreciate some help. I haven't worked with this kind of stuff before. Here are some code snippets that can help:

EDITED .js file:

    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 }))';
    });;
};

EDITED 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>
}

EDITED 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");
           
    }

解决方案

File cannot be passed as a querystring, which will cause the payload format is in an unsupported format. This will result in a 415 error.

In your Export method(IActionResult,return a Jsonresult):

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

Then in your Download method:

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

In your 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;
            }
        });

这篇关于Ajax到MVC POST请求:重定向问题,“页面无法正常工作"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆