MVC 5 - RedirectToAction Not Redirecting

余生长醉 提交于 2019-12-08 16:01:07

问题


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

回答1:


try

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



回答2:


In addtion to Nalaka526's answer: if we look into the documentation for RedirectToAction we can see that it's an instance method of the Controller class which has RedirectToRouteResult as return type, which derives from ActionResult which indicates that we have to return it, just like we return View and PartialView for example.




回答3:


  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.



来源:https://stackoverflow.com/questions/20491271/mvc-5-redirecttoaction-not-redirecting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!