Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect to action in void function

If I have

public ActionResult Join(int? id)
{
   if (id == null)
   {
     return RedirectToAction("Index");
   }

   return View();
}

It works well. How can I make this code reusable? I must call it in many actions. I've tried this:

public ActionResult Join(int? id)
{
    isNull(id);

    return View();
}

public void isNull(int? id)
{
    if (id == null)
    {
        RedirectToAction("Index");
    }
}

But it doesn't redirect.

like image 979
gsiradze Avatar asked Aug 11 '26 13:08

gsiradze


1 Answers

You could do some functional programming:

protected ActionResult WithID(int? arg, Func<int, ActionResult> logic)
{
  if (arg == null)
  {
    return RedirectToAction("Index");
  }

  return logic(arg.Value);
}

invoked like this:

public ActionResult Join(int? arg)
{
  return WithID(arg, (id) => 
  {
    return View();
  });
}
like image 154
Gene Avatar answered Aug 14 '26 19:08

Gene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!