22

I'd like to send multiple parameters to an action in ASP.NET MVC. I'd also like the URL to look like this:

http://example.com/products/item/2

instead of:

http://example.com/products/item.aspx?id=2

I'd like to do the same for sender as well, here's the current URL:

http://example.com/products/item.aspx?id=2&sender=1

How do I accomplish both with C# in ASP.NET MVC?

3 Answers 3

28

If you're ok with passing things in the query string, it's quite easy. Simply change the Action method to take an additional parameter with a matching name:

// Products/Item.aspx?id=2 or Products/Item/2
public ActionResult Item(int id) { }

Would become:

// Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1
public ActionResult Item(int id, int sender) { }

ASP.NET MVC will do the work of wiring everything up for you.

If you want a clean looking URL, you simply need to add the new route to Global.asax.cs:

// will allow for Products/Item/2/1
routes.MapRoute(
        "ItemDetailsWithSender",
        "Products/Item/{id}/{sender}",
        new { controller = "Products", action = "Item" }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to set the appropriate definitions for the route in your global.asax.
@Reza - I've added the URLs as comments in the code. If you want a cleaner URL, you need to add a custom route to global.asax.cs.
13

If you want a pretty URL, then add the following to your global.asax.cs.

routes.MapRoute("ProductIDs",
    "Products/item/{id}",
    new { controller = Products, action = showItem, id="" }
    new { id = @"\d+" }
 );

routes.MapRoute("ProductIDWithSender",
   "Products/item/{sender}/{id}/",
    new { controller = Products, action = showItem, id="" sender="" } 
    new { id = @"\d+", sender=@"[0-9]" } //constraint
);

And then to use the needed actions:

public ActionResult showItem(int id)
{
    //view stuff here.
}

public ActionResult showItem(int id, int sender)
{
    //view stuff here
}

Comments

4

you can use any route rule for example:

{controller}/{action}/{param1}/{param2}

also you can use get params like :baseUrl?param1=1&param2=2

and check this link, i hope it will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.