Stacker
Stacker

Reputation: 8237

Generate Url in MVC from Code Behind

Lets say i`m in an action method and i want to generate a string like this :

http://www.myhost.com/Home/Index?Id=1

i want to save this to DB so i was wondering if there is any formal way to generate it instead of building it up myself.

I`m using MVC3

thanks in advance.

Upvotes: 7

Views: 7291

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could use the Url property of the controller:

public ActionResult Foo()
{
    string url = Url.Action("Index", "Home", new { id = 1 });
    // TODO: save to DB
}

and if you need an absolute url just use the proper overload:

string url = Url.Action("Index", "Home", new { id = 1 }, "http");

Upvotes: 15

Related Questions