Shah
Shah

Reputation: 71

Dynamic Routing in mvc

Recently I attend on interview, he was asking about dynamic routing in mvc.

Question was how to dynamically route certain action method depending upon the parameter string or int.

for example :

Public ActionResult Add(datatype variable)
{  
    //depending upon the Value he was asking how to redirect.
}

Upvotes: 0

Views: 1031

Answers (1)

Aydin
Aydin

Reputation: 15314

Redirects aren't handled by Routing, it's handled by the Actions that are executed.

I suppose what he meant was how do you create Routing rules to execute Action Foo if the data type is a string, and how do you execute action Bar if the data type is an int.

You use Routing Constraints, below I've added a screenshot of all supported constraints.

This is how you would use them

public class HomeController: Controller
{
    // foobar.com/home/123
    [Route("home/{id:int}")]
    public ActionResult Foo(int id)
    {
        return this.View();
    }

    // foobar.com/home/onetwothree
    [Route("home/{id:alpha}")]
    public ActionResult Bar(string id)
    {
        return this.View();
    }
}

More information can be found here.

List of supported routing constraints

Upvotes: 5

Related Questions