Pelle
Pelle

Reputation: 2785

ASP.NET MVC 4 Remember page index

In a ASP.NET MVC 4 app I have a view with a paged list (just a simple table, no telerik grid or anything like that). New values are fetched from the database when the user pages through the list.

On every row in that table there is an edit button, when clicking the button you are presented with an edit view and when you click save in that view you are redirected back to the view with the paged list.

The urls for the list view looks like this

http://localhost/Items/Page/1
http://localhost/Items/Page/2

The route looks like this

routes.MapRoute(
        name: "ItemsList",
        url :"Items/Page/{page}",
        defaults: new { controller = "Items", action = "Index", page = 1 },
            constraints: new {page = @"\d+"}
        );

My question is this: what is the preferred, most common way to store away the referring url, so when done editing an item, I can redirect the user back to the correct url

http://localhost/Items/Page/2

and not just to

http://localhost/Items

I've tried splitting up

Request.UrlReferrer.PathAndQuery

and storing those values around, and then build the url from those values but I have a feeling there is a much better solution to this problem. Any suggestions?

Update

Right now I'm thinking that I could put the UrlReferrer.PathAndQuery (if there are any values) as a property on the view model for the edit screen and then use that when deciding on where to redirect after a save.

Any thoughts out there on that approach?

Upvotes: 1

Views: 1642

Answers (1)

Pelle
Pelle

Reputation: 2785

Here is my final solution to the problem, it's not super elegant but it works. I added a property to the View model that could store the url. That value get's stored in a hidden field.

public class SkillEditModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string RedirectBackToUrl { get; set; }
}

In the controller Edit(GET) method I store the value with the view model

if (!Request.UrlReferrer == null)
{
    model.RedirectBackToUrl = Request.UrlReferrer.PathAndQuery;
}

And finally after saving the changes in Edit (POST) I did this

if (!string.IsNullOrWhiteSpace(model.RedirectBackToUrl))
{
    return new RedirectResult(model.RedirectBackToUrl);
}

return RedirectToAction("Index");

Upvotes: 1

Related Questions