views:

1983

answers:

3

http://localhost:50034/Admin/Delete/723

Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything?

Thanks.

+1  A: 
public ActionResult Details(int? Id)
{
     if (Id == null)
           return RedirectToAction("Index");
     return View();
}
IceHeat
+4  A: 

I am not sure what you mean, do you mean that the url http://localhost:50034/Admin/Delete/ is generating an exception?

Try setting the id parameter as nullable, like this:

public class MyController : Controller
{
  public void Delete(int? id)
  {
    if (!id.HasValue)
    {
      return RedirectToAction("Index", "Home");
    }

    ///
  }
}
Torkel
A: 

Assuming that you are using the default routing rules:

  routes.MapRoute(
     "Default",  // Route name
     "{controller}/{action}/{id}",  // URL with parameters
     new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
   );

then create your Delete method with a nullable int (int?) for the id parameter similar to

public ActionResult Delete(int? id)
{
   if (id.HasValue)
   {
      // do your normal stuff 
      // to delete
      return View("afterDeleteView");
    }
    else
    {
      // no id value passed
      return View("noParameterView");
    }

}

Matthew