Reputation: 43
I have a table with some ids, and i want in default.aspx to open a certain page.aspx with a form, depending on the id.
What i have now is:
if(id_table ==1) {
response.redirect("PageBla.aspx");
}
if(id_table==2) {
response.redirect("Page21231.aspx");
}
if(id_table==6) {
....
}
etc etc....
this is simple if i have small number of ids to check. But i will have dozens of ids to check. Is there any programming pattern or any other method of doing this without dozens of ifs or switchs/cases?
Thanks in advance
EDIT: "=" was substituted with "==".
Upvotes: 3
Views: 284
Reputation: 1540
Just create a simple array of the URLs like this:
string[] urls = {"PageBla.aspx", "Page21231.aspx"};
response.redirect(urls[id_table]);
If you have a more complex use case, another option is to use Convention over configuration. You can do it like that:
Your redirect code will be as simple as:
Response.Redirect(tableId + ".asxp");
Upvotes: 5
Reputation: 15931
Another option is to store the page in the table, select the page to redirect to.
Upvotes: 0
Reputation:
Keep links in a Dctionary:
Dictionary<int, string> links =
new Dictionary<int, string>()
{
{ 1, "One.aspx" },
{ 2, "Two.aspx" },
{ 3, "Three.aspx" }
};
and use the like:
Response.Redirect(links[id_table]);
Upvotes: 1
Reputation: 3883
you can use The Factory Design Pattern that doesn't reduce ifs statements but it encapsulate it.
Update
You can combine the other answers with this pattern to get well written code
Upvotes: 1
Reputation: 62276
Use a Dictionary<K,V>
, instead, like, mor or less, a pseudocode:
var dic = new Dictionary<int, string> { {1, "PageBla.aspx"}, {2, "Page21231.aspx"}..}
and after in code:
response.redirect(dic[id_table]);
Upvotes: 3
Reputation: 164331
It would be quite easy to have a lookup containing the ID's and urls. It could be in a database for flexibility, but you could also just throw them in a dictionary now, and add the database part later, if you find you need it.
You could declare the lookup as a field:
private static readonly Dictionary<int, string> redirectLookup = new Dictionary<int,string> {
{1, "PageBla.aspx"},
{2, "Page21231.aspx"},
// .....
{6, "somepage6.apx"}
};
And in your redirect logic:
string redirect;
if (redirectLookup.TryGetValue(id_table, out redirect))
Response.Redirect(redirect);
else
// some default action when that ID was not mapped.
Upvotes: 5