Redirecting from cshtml page

前端 未结 4 975
执念已碎
执念已碎 2020-12-18 18:12

I want to redirect to a different view depending on the result of a dataset, but I keep getting returned to the page I am currently on, and can\'t work out why. I drop into

相关标签:
4条回答
  • 2020-12-18 18:54

    Would be safer to do this.

    @{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

    So the controller for that action runs as well, to populate any model the view needs.

    Source
    Redirect from a view to another view

    Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

    0 讨论(0)
  • 2020-12-18 19:06

    Change to this:

    @{ Response.Redirect("~/HOME/NoResults");}
    
    0 讨论(0)
  • 2020-12-18 19:07

    You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } ).. Note:- you can add as many parameter as required.

    @Html.ActionLink("MethodName", new { parameter = Model.parameter })

    0 讨论(0)
  • 2020-12-18 19:10

    This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.

    [ChildActionOnly]
    public ActionResult Results() 
    {
        EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
        bool anyRows = custs.Any();
    
        if(anyRows == false)
        {
            return View("NoResults");
        }
        else
        {
            return View("OtherView");
        }
    }
    

    Modify NoResults.cshtml to a Partial.

    And call this as a Partial view in the parent view

    @Html.Partial("Results")
    

    You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3

    The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC

    0 讨论(0)
提交回复
热议问题