2

I am trying to implement POST-Redirect-GET in MVC using multiple named parameters.

I can do this with one parameter:

return RedirectToAction("MyGetView", new { bookId = id });

I could hardcode multiple parameters:

return RedirectToAction("MyGetView, new {bookId = id1, bookId=id2});

But how do I get from an IEnumerable< int> of Ids, which is of variable length, to a correct query string without constructing it by hand?

My current code looks like this:

var querystring= string.Join("", BookIds.Select(x => string.Format("bookId={0}&", x)));
querystring= querystring.Trim('&');

return Redirect("MyGetView?" + querystring);

It works fine, but it seems like there should be a better way.

(I want the parameters to be visible in the URL, so that users can bookmark the page. I believe this means I cannot use TempData.)

Ollyver
  • 359
  • 2
  • 14

1 Answers1

1

First, it's not wrong to use query parameters where the ASP.NET MVC Routes fail to work, and they do with arrays (basically). How is your "clean" URL route supposed to look like?

Example: /Books/View/6 (Works nice for one Book, 6 is the int ID)
But what do you want to have for multiple Books? /Books/View/6,5,134 maybe?

In this case you could just use your own convention of formatting the Url as a list of IDs.

Your redirect would look like: return RedirectToAction("View", "Book", new { Id = allIds.Join(",") });

And your View action can support this:

public ActionResult View(string id)
{
    if (id == null)
        throw new Exception... // Not expected

    var ids = id.Split(new char[]{ ',' });

    // Further processing...
}

If your're not satisfied with this approach (you might have issues when number of items is getting bigger) you can see what others tried, but it's basically what you already do, or I'm not sure if the other solutions are worth the effort.

Community
  • 1
  • 1
thmshd
  • 5,729
  • 3
  • 39
  • 67