Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Redirecting back to page when no parameter is given to URL

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.


2 Answers

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

    ///
  }
}
like image 92
Torkel Avatar answered Dec 31 '25 18:12

Torkel


public ActionResult Details(int? Id)
{
     if (Id == null)
           return RedirectToAction("Index");
     return View();
}