简体   繁体   中英

MVC 5 - RedirectToAction Not Redirecting

Hi I have a problem with my RedirectToAction not redirecting. My code successfully hits a breakpoint placed on the Redirect so I can confirm it is being called. Nothing seems to happen however.

I have tried looking at the network traffic in Chrome and there doesn't seem to be anything obvious. I must be missing something simple!

    //
    // POST: /Blog/CreateBlog
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateBlog(BlogViewModel model)
    {
        var userId = User.Identity.GetUserId();
        model.UserId = userId;

        if (ModelState.IsValid && model.UserId != null)
        {
            Mapper.CreateMap<BlogViewModel, Blog>();
            if (_blogProcess.CreateBlog(Mapper.Map<BlogViewModel, Blog>(model)))
            {
                RedirectToAction("Index", "Blog");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

尝试

return RedirectToAction("Index", "Blog");

除了Nalaka526的答案之外:如果我们查看RedirectToAction文档 ,我们可以看到它是Controller类的一个实例方法,它将RedirectToRouteResult作为返回类型,它派生自ActionResult ,它表示我们必须return它,就像我们返回一样例如, ViewPartialView

  1. If you are using @using(Html.BeginForm("Index","Blog"..) on the view page then

     public ActionResult CreateBlog(BlogViewModel model) { .... return RedirectToAction("Index", "Blog") } 

    should work.

  2. If you are using Ajax.BeginForm , then you need to redirect to a new action/url from javascript OnSuccess event. sample code for your view

     @using (Ajax.BeginForm("Index", "Blog", new AjaxOptions { HttpMethod = "post" , OnSuccess="RedirectFunction"} function RedirectFunction(data) { window.location.href = “Index”; } 

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM