7

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.

1 Answer 1

15

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");
Sign up to request clarification or add additional context in comments.

4 Comments

funny thing is the only Url i have is under System.Security.Policy; and it doesn't have Action Method
@Stacker, the code example I have shown is inside a controller action. Controller actions belong to a controller. Controllers derive from the Controller class. The Controller class has an Url property. This is what you should use. You should not try to generate urls just anywhere in your application which is what I suppose you are doing, like in the Model for example. If some part of your code needs an url, you should generate this url in the controller and pass it as parameter to this part of the code that needs it.
@DarinDimitrov, I know this is off-topic for this answer, but how would you unit test Foo()? Wouldn't you need to mock the HttpContext / HttpRequest?
@olivehour, yes, exactly, you will mock the HttpContext.

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.