Redirecting to an action in a 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 have to call this in many activities. 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 get redirected.
+3
source to share
4 answers
You can do some functional programming:
protected ActionResult WithID(int? arg, Func<int, ActionResult> logic)
{
if (arg == null)
{
return RedirectToAction("Index");
}
return logic(arg.Value);
}
called like this:
public ActionResult Join(int? arg)
{
return WithID(arg, (id) =>
{
return View();
});
}
+1
source to share
What you are trying to do is return the function earlier, in another function. It's impossible. This does not mean that IsNull
it is impossible to take out , 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 can be called as
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 another question.
You might want to use Id in it, so you end up with 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 this further
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 have definitely left the field of good ideas.
+1
source to share