gsiradze
gsiradze

Reputation: 4733

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.

Upvotes: 3

Views: 3747

Answers (4)

Cenk Taylan Düz
Cenk Taylan Düz

Reputation: 59

The second method is not returning ActionResult. make void to Action result and return RedirectToAction

Upvotes: -1

Martijn
Martijn

Reputation: 12102

What you are trying to do is to return your function early, in a different function. That is impossible. That is not to say that taking out the IsNull is impossible, but rather impractical. A possible solution could be

public ActionResult isNull(int? id, Func<ActionResult> _else) {
  if (id == null) {
    return RedirectToAction("Index");
  } else {
    return _else();
  }
}

which could be called like

public ActionResult Join(int? id){
  Func<ActionResult> ifNotNull = () => {
    //do whatever you want here, in your case
    return View();
  }
  return isNull(id, ifNotNull);
}

or directly

public ActionResult Join(int? id){
  return isNull(id, () => View());
}

Whether this is a good idea is a different question.

You will probably want to use Id in it though, so you'll get something like

public ActionResult isNull(int? id, Func<int, ActionResult> _else) {
      if (id == null) {
        return RedirectToAction("Index");
      } else {
        return _else(id.value);
      }
}

You could abstract that out further to

public ActionResult isNull<T>(T id, Func<T, ActionResult> _else) where T: class {
      if (id == null) {
        return RedirectToAction("Index");
      } else {
        return _else(id);
      }
}

and

public ActionResult isNull<T>(Nullable<T> id, Func<T, ActionResult> _else) {
      if (id == null) {
        return RedirectToAction("Index");
      } else {
        return _else(id.value);
      }
}

but by now, we definitely have left the realm of good ideas.

Upvotes: 1

Gene
Gene

Reputation: 4232

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

Upvotes: 2

Matt Houser
Matt Houser

Reputation: 36073

If your Join action requires id, then don't make id nullable:

public ActionResult Join(int id)
{
   // use id

   return View();
}

Upvotes: 1

Related Questions