Asp.net mvc - Route for a string or int (e.g. type / 23 or / type / hats)

I have the following case when I want to accept the following routes

 '/type/view/23' or '/type/view/hats'

where 23 - Id for hats.

The controller looks something like this:

public class TypeController
{ 
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult View(int id)
    {
      ...
    }
}

Now, if they do not have 23 problems. If they pass hats, I have a job. Now I was wondering, in this case, I would translate the hats to 23 using an ActionFilter that looks to see if the value will be passed as id, is int (if so, check that it exists in the database) or if this line looks like for the database the data for which the identifier of the row that was transmitted is. In any case, if no match is found, I would like to redirect the user to another action.

Firstly, this is the approach that I called right, and secondly, you can do a redirect from ActionFilter.

+5
2

, . , id int. , id, . , .

public class TypeController
{ 
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult View(string id)
    {
       Product product = null;
       int productID = -1;
       if (int.TryParse( id, out productID))
       {
           product = db.Products
                       .Where( p => p.ID == productID )
                       .SingleOrDefault();
       }
       else
       {
           product = db.Products
                       .Where( p => p.Name == id )
                       .SingleOrDefault();
       }

       if (product == null)
       {
           return RedirectToAction( "Error" );
       }
       ...
    }
}

, , , , , / , , , . , - , - , - . , , , , , int - , , , , , . , , - .

+4

, . , , , , .

,

return RedirectToAction("MyProfile", "Profile");

RedirectToAction, .., .

, , , .

0

All Articles