【问题标题】:How can i use RedirectToAction within $.ajax POST?如何在 $.ajax POST 中使用 RedirectToAction?
【发布时间】:2017-06-10 15:24:03
【问题描述】:

我正在尝试使用控制器的以下方法进行重定向:

[HttpPost]
    public async Task<IActionResult> CreateSchedinaB([FromBody]ListAssociazioni listAss)
    {
        var userr = await _manager.GetUserAsync(User);
        var listSchedine = await _context.Schedine.ToListAsync();

        List<Associazioni> listAssocia = new List<Associazioni>();
        Schedine schedina = new Schedine();

        bool doppione = false;

        foreach (var item in listSchedine)
        {
            if (listAss.NomeS == item.Nome)
            {
                doppione = true;
            }
        }
        if (doppione == false)
        {
            schedina.Nome = listAss.NomeS;
            schedina.KsProfile = userr.ProfileId;
            schedina.Id = _context.Schedine.Count() + 1;
            _context.Schedine.Add(schedina);
        }
        else
        {
            ViewData["Success"] = "Data was saved successfully.";

            return RedirectToAction("Index");
        }
        foreach (var item in listAss._listAssoc)
        {
            var giocata = _context.Giocate.Where(c => c.Id == item.KsGiocata).First();
            var partita = _context.Calendario.Where(c => c.Id == item.KsPartita).First();

            Associazioni tmp = new Associazioni { KsGiocataNavigation = giocata, KsPartitaNavigation = partita, KsSchedinaNavigation = schedina };
            _context.Associazioni.Add(tmp);
        }
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

我不在视图中使用 asp-action 调用该方法,而是在 $.ajax post 中以这种方式调用该方法:

-查看:

`<div class="form-group">
    <label asp-for="schedine.Nome" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input id="nomeSchedina" asp-for="schedine.Nome" class="form-control" />
        <span asp-validation-for="schedine.Nome" class="text-danger"></span>
    </div>
</div>


<a class="btn btn-default" onclick="InviaServer()" >CREA</a>`

-JS:

function InviaServer() {
    var Nomes = $("#nomeSchedina").val();
    if (Nomes == "" || Nomes == null) {
        window.alert("Dai un nome alla tua schedina!");
        return;
    }
    var listadef = {"NomeS": Nomes, "_listAssoc": json};
    $.ajax({    // Send list to controller
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        url: "/Logged/CreateSchedinaB/",
        type: "POST",
        data: JSON.stringify(listadef),
        success: function (response) {
            console.log(response);
        }
    });
}

控制器 - 索引

[HttpGet]
        public IActionResult Index()
        {
            return View();
        }

问题是该方法并没有重定向到页面而是在浏览器控制台中发送页面...为什么?

对不起我的英语......我是一个“绝对初学者”

【问题讨论】:

  • 您是否尝试在控制器中调用不同的操作
  • 你在哪里“索引”操作?
  • 在同一个控制器中
  • 一切正常,但页面打印在控制台中。
  • 将重定向网址发送到客户端,然后在客户端执行location.href = redirecturl

标签: javascript c# jquery ajax asp.net-core


【解决方案1】:

当您进行 Ajax 调用时,您有责任处理来自服务器的响应。对于您的情况,您可以执行以下操作。:

[HttpPost]
public ActionResult DoSomeStuffAndRedirect()
{
     //Do some stuff you want

     return Json(Url.Action("Contact"), JsonRequestBehavior.AllowGet); 
     //Note: Url.Action(...) would give you fully qualified url based on to an action and it adheres to the defined route templates.
}

在客户端你可以这样做:

$.ajax({    // Send list to controller
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            url: "/Home/DoSomeStuffAndRedirect/",
            type: "POST",
            data: {},
            success: function (response) {
                location.href = response;
            }
});

希望这能给你一些想法。

【讨论】:

  • 我不能使用 JsonRequestBehavior 因为我没有找到 System.Web.Mvc 引用...帮助
  • 没有JsonRequestBehavior 它也应该适用于您的情况。我很好奇,为什么它对你不可用,因为如果没有 System.Web.Mvc 引用,你的 MVC 实验就不会走这么远!
  • return Ok(jsonObject)
  • 可能是因为我用的是 AspNetCore?
【解决方案2】:

你做了一个 ajax 调用,它不能把你重定向到别的东西。

你需要在ajax成功中使用这样的东西:

 success: function (response) {
         document.location = '/Logged/index/';
        }

同样在后端方法 CreateSchedinaB 中不要重定向(它没用,只是返回一些内容到您的 ajax 方法响应中,例如关于重定向的结果或错误)

【讨论】:

  • 谢谢,这个答案非常有用,但我需要从控制器重定向它,因为我做了检查!
  • 在您的控制器中进行检查,然后将检查状态报告给您的 ajax,基于此进行重定向或显示错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多