How to append ID to the end of the URL using RedirectToAction in MVC

Home > Search > How-to
  by

When creating a new MVC project using Entity Framework, by default, when clicking on Save at www.example.com/Example/Edit/1, you are redirected to www.example.com/Example/Index. Let's change this behavior to redirect to www.example.com/Example/Details/1.

By default, the /Controllers/Example.cs will have an [httpPost] like this:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Exclude = "")] Example example)
        {
            if (ModelState.IsValid)
            {
                db.Entry(example).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction(example);
            }
            return View(example);
        }

 

The following changes are needed to redirect to www.example.com/Example/Details/1.

  • Add int? id to the public ActionResult
  • Replace return RedirectToAction (example) with return RedirectToAction("Details", new { id = id });
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Exclude = "")] int? id, Example example)
        {
            if (ModelState.IsValid)
            {
                db.Entry(example).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Details", new { id = id });
            }
            return View(example);
        }

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments