ASP.NET MVC Return to Previous Page

Posted by Jason Enochs on Stack Overflow See other posts from Stack Overflow or by Jason Enochs
Published on 2012-03-19T15:26:36Z Indexed on 2012/03/19 18:03 UTC
Read the original article Hit count: 284

Filed under:
|
|

I have a basic Edit method in my controller that redirects back to a top level listing (“Index”) when the edit succeeds. Standard setup after scaffolding.

I am trying to change this Edit method to redirect back to the previous page (not Index). Since my Edit method is not using the default mapped input parameter “id”, I am using that to pass the previous URL.

In my Edit “get” method, I use this line to grab the previous URL and it works fine: ViewBag.ReturnUrl = Request.UrlReferrer.AbsoluteUri;

I send this return URL to the Edit “post” method by using my form tag like this: @using (Html.BeginForm(new { id = ViewBag.ReturnUrl }))

Now this is where the wheels fall off. I can't seem to get the URL parsed from the id parameter properly.

UPDATE****

Using Gary's example as a guide, I changing my parameter name from "id" to "returnUrl" and used a hidden field to pass my parameter. Lesson: Only use the id parameter how it was intended to be used...keep it simple. It works now... Here is my updated code.

    //
    // GET: /Question/Edit/5

    public ActionResult Edit(int id)
    {
        Question question = db.Questions.Find(id);
        ViewBag.DomainId = new SelectList(db.Domains, "DomainId", "Name", question.DomainId);
        ViewBag.Answers = db.Questions
                            .AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.Text,
                                Value = d.QuestionId.ToString(),
                                Selected = question.QuestionId == d.QuestionId
                            });
        ViewBag.returnUrl = Request.UrlReferrer;
        ViewBag.ExamId = db.Domains.Find(question.DomainId).ExamId;
        ViewBag.IndexByQuestion = string.Format("IndexByQuestion/{0}", question.QuestionId);
        return View(question);
    }

    //
    // POST: /Question/Edit/5

    [HttpPost]
    public ActionResult Edit(Question question, string returnUrl)
    {
        int ExamId = db.Domains.Find(question.DomainId).ExamId;
        if (ModelState.IsValid)
        {
            db.Entry(question).State = EntityState.Modified;
            db.SaveChanges();
            //return RedirectToAction("Index");
            return Redirect(returnUrl);
        }
        ViewBag.DomainId = new SelectList(db.Domains, "DomainId", "Name", question.DomainId);
        return View(question);
    }

and I changed my form tag to this:

@using (Html.BeginForm())
{
    <input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" />

Thanks Gary

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET