Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have several ActionResults where I implemented below condition.
C#
public async Task<ActionResult> Status(int Id)
{
      if (Id <= 0)
      {
          TempData["Errors"] = "Invalid data";

          return RedirectToAction("Error", "Dashboard");
      } ....
 }

I want to move this complete if condition to a separate method and call it where needed. Please advice

What I have tried:

Below is what I tried but redirection does not work

C#
public async Task<ActionResult> Status(int Id)
        {
            UtilityHelpder helper = new UtilityHelper();
            await helper.IdCheck(this, Id);

            ...
        }


public class UtilityHelper
    {
        public async Task IdCheckHelper(Controller controller, int Id)
        {
            if (Id <= 0)
            {
            controller.TempData["Errors"] = "Invalid data";
            controller.HttpContext.Response.Redirect("/Dashboard/Error");
            }
        }
    }
Posted
Updated 12-Feb-23 5:30am

1 solution

May be the issue with your code is that you are redirecting to "/Dashboard/Error" using HttpContext.Response.Redirect(). Since you are calling this method from a different class, it does not have access to the URL of your current request, which is why the redirection does not work.

Instead of using HttpContext.Response.Redirect(), you can return a RedirectToActionResult from your IdCheckHelper method.

example:
C#
if (Id <= 0)
      {
          controller.TempData["Errors"] = "Invalid data";
          return new RedirectToActionResult("Error", "Dashboard", null);
      }
      return null;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900