开发者

asp.net mvc - category/1 to category/fruit... right approach?

开发者 https://www.devze.com 2023-01-19 08:56 出处:网络
suppose I have 3 categories 1, 2, 3 named fruit, vegetable and grain. Right now I have domain.com/category/1 which would take me to fruit\'s page and so on...

suppose I have 3 categories 1, 2, 3 named fruit, vegetable and grain.

Right now I have domain.com/category/1 which would take me to fruit's page and so on...

Now I would like to domain.com/category/fruit to take me to fruit's page because that looks nicer and categories are very few like 3 or 4 max... so I don't plan on looking at database to see what categoryid refers to what name.

Should I just use a global enum/array? (any examples?)

It just seemed weird, because I have a dropdown that lists all the categories and I look at the selected integer value of the category (assume 1) and pass it on to Category ActionResult and then the actionresult looks at "fruit" and then converts it back to 1... so I am going back and forth just so that URL would look nice, which makes me wonder if I should do some kind of URL routing in global.asax for this?

Or maybe I should use web.con开发者_运维百科fig to declare fruit = 1 and so on...?

There are several ways to do this I guess, but I want to know the most efficient way.


I do something like:

/category/1/fruit
/category/2/vegetable

{action}/{id}/{*extra}

You can do it your way, but then you have to do it just like you're saying. Probably would want to index the field if you're doing a db lookup.

With keeping the id value in there you don't have to index the field, or do the weird lookup. The only thing you lose is for people to guess your other category names and type them in manually. The only person that is really going to care about that is you.

If you really don't want the number and don't want to deal with a database, just create a Hashtable convert the "id" to a value:

var categories = new Hashtable();
categories.Add("fruit", 1);
categories.Add("vegetable", 2);

Then use fruits[id] to get your number back.


Why do you need to convert the string (categoryName) back to an int (categoryId)? Why not just use the string to get the data you need:

Service Call:

Data GetDataByCategoryName(string categoryName)
{
   return repository.GetSingle(x => x.CategoryName == categoryName);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号