如何在$ .ajax POST中使用RedirectToAction?

时间:2017-06-10 15:24:03

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

我尝试使用以下控制器方法重定向:

[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中以这种方式发布:

-view:

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

CONTROLLER - INDEX

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

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

对不起我的英语......我是一个绝对的初学者&#34;

2 个答案:

答案 0 :(得分:0)

你进行ajax调用,它无法将你重定向到别的东西。

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

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

同样在后端方法中,CreateSchedinaB不会重定向(它是无用的,只需返回一些你的ajax方法响应,例如关于重定向或错误的结果)

答案 1 :(得分:0)

当您进行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;
            }
});

希望这能让你有所了解。