Bootstrap FreeKB - MVC - Append ID to the end of the URL using RedirectToAction
MVC - Append ID to the end of the URL using RedirectToAction

Updated:   |  MVC articles

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

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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